java - 重新初始化 spring @Autowire bean

标签 java spring autowired spring-bean

我有一个场景,我需要在启动期间根据应用程序配置初始化 bean。后来,由于基于事件获取动态配置,我必须更新 bean。

此 Bean 无法更新,只能用新实例替换。

使用 new 运算符是否仅初始化本地实例,还是会更改 bean?

@Component
public class TestComp {

  @Autowired
  private BeanA beanA;

  public void updateBean() {
    beanA = new BeanA("new value");
  }

}

我在另一个类中引用了该 bean,并在使用 new 初始化它后进行了检查。它反射(reflect)了新对象。但是,如果确实如此,我需要专家的确认。

最佳答案

I have a scenario where I need to initialize a bean based on application configuration during startup.

没关系。单例作用域在这里是一个不错的选择。

Later, due to dynamic configuration fetched based on an event, I have to update the bean.

这是一个问题。在上下文中更新 bean 是一个复杂的过程:您需要删除现有的 bean 定义,添加新的定义,并更新所有与该 bean 相关的 bean(重新初始化这些组件,刷新上下文)。从技术上讲,这是可能的,并且 Spring Cloud 的 @RefreshScope 已经简化了它。

Does using new operator initialize only the local instance or will it change the bean?

它仅影响此类中的字段。没有人意识到这一变化。 ApplicationContext#getBean 仍然会返回旧对象,并且所有组件都将(或已经)使用旧实例进行初始化。

I referred the bean in another class and checked after I initialized it with new. It reflected the new object.

这不可能是真的。可能它引用的是 TestComp#beanA 字段,而不是它自己的 BeanA 字段。

我建议的解决方案是 to define a custom bean scope基于您收到的事件。它将保持 bean 和上下文更新。

关于java - 重新初始化 spring @Autowire bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52655973/

相关文章:

java - 使用抽象类

java - Spring 启动 : Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

java - 为什么要 "Make autowired dependencies explicit"?

java - Resteasy 与 Spring 集成的问题

Eclipse 在 "populate auto detected configs"时崩溃(无响应)

java - Spring 没有匹配类型的 bean,预计至少有 1 个 bean

java - Spring @autowired 返回空值

java - 如何显示用户输入的最大和最小数字?

java - java无法删除文件?

java - 接受字符串值列表的 Spring 验证