前言:
- 若java类不是spring bean不能使用@Value(${})注解获取配置文件属性值。
- SpringBoot如何读取非缓存区配置信息的配置文件中配置。
- @PostContruct是spring框架的注解,在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在spring容器初始化的时候执行该方法。
业务需求:
项目中以前读取配置文件使用静态代码块来加载配置,不能根据运行环境区分配置文件读取,因此需要改造代码,区分不同环境读取对应的配置信息到缓存区。
- 之前的代码:
public class GetPropsUtils {
private final Map<String, String> map = new HashMap<>();
static {
try {
Properties properties = new Properties();
properties.load(GetPropsUtils.class.getClassLoader().getResourceAsStream("security.properties"));
for (Entry<Object, Object> entry : properties.entrySet()) {
map.put(entry.getKey().toString(), entry.getValue().toString());
}
} catch (Exception e) {
log.error("read properties error", e);
}
}
}
- 改造后:
1、将security.properties拆分成security-test.properties和security-prod.properties
2、在application.yml中添加配置:
spring:
profiles:
active: dev/prod
3、改造代码,使用@Component将类注册到bean容器中,@Value注解获取缓存区环境标识配置,改写静态代码块,使用@PostConstruct注解初始化init方法。
@Component
public class GetPropsUtils {
private final Map<String, String> map = new HashMap<>();
@Value("${spring.profiles.active}")
private String env;
@PostConstruct
public void init() throws Exception {
Properties properties = new Properties();
properties.load(GetPropsUtils.class.getClassLoader().getResourceAsStream("security-" + env + ".properties"));
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
map.put(entry.getKey().toString(), entry.getValue().toString());
}
}
}
后记:还有一种解决方式是将不同运行环境配置文件独立出来,请参考链接: springboot启动读取外部配置文件.但是我不想独立这个配置文件,于是就有了上面这些东西~~