spring自定义Environment中的属性值

需求背景

在springboot项目中,我们可以在properties文件里配置各种属性,然后在代码里通过@Value方式获取属性值。

比如properties定义

user.ids=XXXXX

代码中使用

 @Value("${user.ids}")
 private String userIds;

这种方式的特点是,除非重启项目,否则通过@Value方式获取的值在项目启动过程中就确定了。

但现在有个需求是:

在项目运行过程中改变属性的值,不能重启项目。

现在我们来实现这个功能。

代码

1.自定义PropertySource并加入Environment

在项目启动时,将OriginTrackedMapPropertySource加入Environment对象。OriginTrackedMapPropertySourcePropertySource的一个实现类。

 @Autowired
 private ConfigurableApplicationContext applicationContext;

 @PostConstruct
    public void initUserIds(){
        Map<String, Object> map = new HashMap<>();
        map.put("userIds", "01393330");
        OriginTrackedMapPropertySource source = new OriginTrackedMapPropertySource("customProperty", map);
        MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
        propertySources.addLast(source);
    }

2.获取自定义PropertySource中的属性

因为Environment对象中有了我们自定义的属性,所以此时不再通过@Value获取了,如下

   @Autowired
    private ConfigurableApplicationContext applicationContext;

    String userIds = applicationContext.getEnvironment().getProperty("userIds");

3.改变PropertySource中的属性

对外暴露接口,传入需要改变的userIds

  public String changeUserIds(String userIds){
        MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
        Map map = (Map)propertySources.get("customProperty").getSource();
        map.put("userIds", userIds);
        return "OK";
  }

调用后Environment对象中userIds就发生了改变

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值