简体   繁体   English

在运行时重新加载 spring bean

[英]reload spring bean during the runtime

I am trying to change bean property value during the runtime.我正在尝试在运行时更改 bean 属性值。

WebConfig网络配置

@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;

    }
}

Changing the value occurs only when the server is rebooted.只有在重新启动服务器时才会更改该值。 Can you suggest example how to achieve bean reloading during the runtime or tell what I'm doing wrong?您能否建议如何在运行时实现 bean 重新加载的示例或告诉我做错了什么? All help appreciated所有帮助表示赞赏

why not inject the service into policy ?为什么不将service注入policy and everytime you call the policy.getMaxLoginAttempts() the call gets delegated to service.getMaxAttempts() .每次您调用policy.getMaxLoginAttempts()该调用都会委托给service.getMaxAttempts() So you get new values returned, without having to reload.因此,您无需重新加载即可返回新值。

So the config looks like this:所以配置看起来像这样:

@Bean
public SecurityPolicy securityPolicy() {
    return new SecurityPolicy(service);
}

And the SecurityPolicy.getMaxLoginAttempts() like this:SecurityPolicy.getMaxLoginAttempts()像这样:

public int getMaxLoginAttempts(){
    return service.getMaxAttempts();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM