我正在尝试在运行时更改 bean 属性值。
网络配置
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
@Autowired
private SecurityService service;
@Bean
public SecurityPolicy securityPolicy() {
SecurityPolicy policy = new SecurityPolicy();
//takes data from db, it works fine
policy.setMaxAttempt = service.getMaxAttempts();
return policy;
}
}
Controller
@Controller
public class SecurityPolicyController {
@Autowired
private SecurityPolicy policy;
@Autowired
private ApplicationContext context;
@Autowired
private SecurityService service;
@RequestMapping(value = "/security")
public ModelAndView update() {
ModelAndView model = new ModelAndView();
//set data to db, it works fine aswell
service.setMaxAttempts(7);
//now i am trying to reload my beans
((ConfigurableApplicationContext)context).refresh();
//something reloading but i still get the same value
System.out.println(policy.getMaxLoginAttempts());
model.setViewName("security");
return model;
}
}
仅当服务器重新启动时才会更改值。 您能否建议示例如何在运行时实现 bean 重新加载或告诉我做错了什么?感谢所有帮助
最佳答案
为什么不将 service
注入(inject)到 policy
中?每次您调用 policy.getMaxLoginAttempts()
时,调用都会委托(delegate)给 service.getMaxAttempts()
。因此,您无需重新加载即可获得返回的新值。
所以配置看起来像这样:
@Bean
public SecurityPolicy securityPolicy() {
return new SecurityPolicy(service);
}
SecurityPolicy.getMaxLoginAttempts()
是这样的:
public int getMaxLoginAttempts(){
return service.getMaxAttempts();
}
关于java - 在运行时重新加载 spring bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46973979/