springboot项目一般使用application.yml配置文件,数据库信息写在里面,做部署时,各个项目可能密码要求不一样需要修改密码,每次修改密码都要打包就比较麻烦,可以增加个外部配置文件进行处理,具体如下:
1、修改Application.java
@ComponentScan(basePackages = {"com.**.x"})
@EnableFeignClients(basePackages = {"com.**.x"})
@SpringBootApplication
@Slf4j
@EnableTransactionManagement
public class ApiApplication {
private static final Logger logger = LoggerFactory.getLogger(PdsApiApplication.class);
public static void main(String[] args) {
//SpringApplication.run(ApiApplication.class, args);
SpringApplication application = new SpringApplication(ApiApplication.class);
// Load external properties file if it exists
String externalConfigPath = "config.properties";
Resource resource = new FileSystemResource(externalConfigPath);
if (resource.exists()) {
logger.info("配置文件存在");
try {
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
PropertySource<?> propertySource = new PropertiesPropertySource("externalConfig", properties);
application.addInitializers(context -> {
ConfigurableEnvironment environment = context.getEnvironment();
environment.getPropertySources().addFirst(propertySource);
});
} catch (IOException e) {
e.printStackTrace();
}
}else{
logger.info("配置文件不存在");
}
// Run the application
application.run(args);
}
}
这段代码检查 config.properties
文件是否存在,如果存在则加载该配置文件并将其添加到 Spring Boot 的环境中。这确保了外部配置会覆盖 application.yml
中的相应配置项。
2、配置文件config.properties如下:
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mysql?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT%2B8&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=xxx
spring.datasource.main.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT%2B8&allowMultiQueries=true
spring.datasource.main.username=root
spring.datasource.main.password=xxx