在运行时更新 bean 属性

Update bean property at runtime

我有一个包含一些配置的 bean:

public class CustomerService{
  private Config config;

  @Required
  public void setConfig(Config config){
    this.config = config;
  }
}

public Config {
  private String login;
  private String password;

  //setters/getters
}

应用-context.xml:

<bean id="config" class="Config"/>
<bean id="customerService" class="CustomerService">
   <property name="config" ref="config"/>
</bean>

并且配置值是在运行时获取的(通过调用 api)。 如何在运行时更新这些值?我可以使用 setter:

来完成吗
customerService.getConfig().setLogin("login");

首先在需要的地方注入你的Spring上下文

@Autowired
ApplicationContext context;

从Spring上下文中获取customerService实例

CustomerService service = context.getBean(CustomerService.class);

在运行时 service 上进行必要的更改

service.getConfig().setLogin("login");

更新:您还可以从上下文中获取您的 Config 实例

context.getBean(Config.class).setLogin("login");