在运行时更新 bean 属性

rom*_*yak 3 java spring spring-ioc

我有一个包含一些配置的 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
}
Run Code Online (Sandbox Code Playgroud)

应用上下文.xml:

<bean id="config" class="Config"/>
<bean id="customerService" class="CustomerService">
   <property name="config" ref="config"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

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

customerService.getConfig().setLogin("login");
Run Code Online (Sandbox Code Playgroud)

And*_*sun 10

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

@Autowired
ApplicationContext context;
Run Code Online (Sandbox Code Playgroud)

customerService从 Spring 上下文获取实例

CustomerService service = context.getBean(CustomerService.class);
Run Code Online (Sandbox Code Playgroud)

service在运行时进行所需的更改

service.getConfig().setLogin("login");
Run Code Online (Sandbox Code Playgroud)

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

context.getBean(Config.class).setLogin("login");
Run Code Online (Sandbox Code Playgroud)