Update bean property at runtime

12,686

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");
Share:
12,686
romanvintonyak
Author by

romanvintonyak

Updated on June 13, 2022

Comments

  • romanvintonyak
    romanvintonyak about 2 years

    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");
    
  • romanvintonyak
    romanvintonyak over 7 years
    what is the scope for Config bean? prototype?
  • romanvintonyak
    romanvintonyak over 7 years
    I meant what should be a proper bean scope?