原本项目中有applicationContext.xml
<!-- 属性文件读入 -->
<bean id="propertyConfigurer" class="XX.XX.XX.SpringPropertiesUtils">
<property name="locations">
<list>
<value>classpath*:config/*.properties</value>
</list>
</property>
</bean>
转为springboot 项目后不想继续使用xml文件加载配置文件,则在启动类中加入
@Bean
public SpringPropertiesUtils getSpringProUtils() {
return new SpringPropertiesUtils();
}
使用这种方式加载后,项目报:
legalArgumentException: Could not resolve placeholder 'jdbc.driver-class-name' in value "${jdbc.driver-class-name}"
看了https://blog.youkuaiyun.com/hannover100/article/details/78124660该贴,知道是由于多个配置文件导致的问题,再在启动类加入
@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
PropertySourcesPlaceholderConfigurer c = new PropertySourcesPlaceholderConfigurer();
c.setIgnoreUnresolvablePlaceholders(true);
return c;
}
后来发现properties文件的属性没有注入到想要加载的类里面,后来新建了一个config专门加载这些文件
@Configuration
public class PropertiesConfig {
@Bean(name="propertyConfigurer")
@ConfigurationProperties(prefix = "XX.XX.XX")
public SpringPropertiesUtils SpringPropertiesUtils(){
SpringPropertiesUtils springPropertiesUtils = new SpringPropertiesUtils();
springPropertiesUtils.setLocations(new ClassPathResource("config/basic.properties"));
return springPropertiesUtils;
}
}
但properties文件好像只能一个一个加载,尝试找到可以一次全部加载的方法。
21.01.26新增
根据不同的启动命令,读取不同的配置文件:
@Bean("propertyConfigurer")
@DependsOn("springContextHolder")
public SpringPropertiesUtils SpringPropertiesUtils(){
SpringPropertiesUtils springPropertiesUtils = new SpringPropertiesUtils();
String active = SpringContextHolder.getApplicationContext().getEnvironment().getActiveProfiles()[0];
if (active.equals("dev")) {
springPropertiesUtils.setLocations(
new ClassPathResource("application.properties"),
new ClassPathResource("application-dev.properties")
);
} else {
springPropertiesUtils.setLocations(
new ClassPathResource("application.properties"),
new ClassPathResource("application-prod.properties")
);
}
return springPropertiesUtils;
}
当启动多个端口时,获取当前服务的端口号:
@Bean("getPortConfigurer")
public static String getPort(){
String port = SpringContextHolder.getApplicationContext().getEnvironment().getProperty("server.port");
return port;
}