Update bean property at runtime

romanvintonyak picture romanvintonyak · Sep 28, 2016 · Viewed 11k times · Source

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");

Answer

Andriy Kryvtsun picture Andriy Kryvtsun · Sep 28, 2016

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");