【问题标题】:How can I update all spring objects after setting new configuration?设置新配置后如何更新所有弹簧对象?
【发布时间】:2016-04-08 13:57:06
【问题描述】:

动态配置更改后如何刷新之前的@Autowiredspring 对象?

// Here is my updateConfig method

GenericApplicationContext context = new GenericApplicationContext();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
reader.loadBeanDefinitions(new ClassPathResource("applicationContext.xml"));
context.refresh();

myApplicationContextAware.setApplicationContext(context);

使用myApplicationContextAware.applicationContext.getBean(MyClass.class) 我可以通过新配置获取新实例,但所有@Autowired 对象仍然包含旧值

有没有办法刷新spring对象?

【问题讨论】:

    标签: java spring dependency-injection configuration autowired


    【解决方案1】:

    您可以为此使用AbstractRefreshableApplicationContext。它提供了在运行时重新加载 bean 配置的方法。

    如果您使用的是 Spring Boot,那么您可以将 @RefreshScope 注释与 spring actuator 一起使用。 Spring 执行器端点 /refresh 重新加载使用 @RefreshScope 注释的 bean。

    【讨论】:

    • Spring Boot 完美运行,谢谢!否则 AbstractRefreshableApplicationContext 对我不起作用,它无论如何都会加载新配置,但即使所有最初自动装配的 bean 都包含旧值
    • 感谢您的确认,我还发现 SO 条目可刷新上下文不会更新对旧 bean 的引用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 2019-09-26
    • 2018-11-27
    • 1970-01-01
    • 2013-10-10
    相关资源
    最近更新 更多