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");
Author by
romanvintonyak
Updated on June 13, 2022Comments
-
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 over 7 yearswhat is the scope for Config bean? prototype?
-
romanvintonyak over 7 yearsI meant what should be a proper bean scope?