需求背景

在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就发生了改变

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐