Search code examples
javaspringspring-ioc

Update bean property at runtime


I have a bean that holds some configuration:

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>

and the config values are obtained at runtime (by calling api). How to update those values at runtime? Can I do it using a setter:

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

Solution

  • Inject your Spring context first in needed place

    @Autowired
    ApplicationContext context;
    

    Obtain customerService instance from Spring context

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

    Do needed changes on service in runtime

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

    UPDATE: you also can obtaine from the context just your Config instance

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