@PostConstruct注解用于方法上,初始化该方法,达到类似静态代码块的效果实例

前言:

  • 若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启动读取外部配置文件.但是我不想独立这个配置文件,于是就有了上面这些东西~~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值