在运行时更新bean属性

3

我有一个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
}

app-context.xml:

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

配置值在运行时通过调用API获取。如何在运行时更新这些值?我可以使用setter来做吗:

customerService.getConfig().setLogin("login");
1个回答

12

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

@Autowired
ApplicationContext context;

从Spring上下文中获取customerService实例。
CustomerService service = context.getBean(CustomerService.class);

在运行时对 service 进行必要的更改。

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

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

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

Config bean的作用域是什么?原型? - romanvintonyak
我的意思是什么是适当的Bean作用域? - romanvintonyak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接