在运行时更新bean属性

时间:2016-09-28 19:22:17

标签: java spring spring-ioc

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

   key col1 col2
0    1    a    e
1    2    b    f
2    3    c    g
3    4    d    h

APP-context.xml中:

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
}

并在运行时获取配置值(通过调用api)。 如何在运行时更新这些值?我可以使用setter来做到这一点:

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

1 个答案:

答案 0 :(得分:3)

首先在所需位置注入Spring上下文

@Autowired
ApplicationContext context;

从Spring上下文中获取customerService实例

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

在运行时

中对service进行必要的更改
service.getConfig().setLogin("login");

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

context.getBean(Config.class).setLogin("login");
相关问题