在运行时重新加载 spring bean

reload spring bean during the runtime

我正在尝试在运行时更改 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
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 注入 policy?每次您调用 policy.getMaxLoginAttempts() 时,调用都会委托给 service.getMaxAttempts()。因此,您无需重新加载即可获得返回的新值。

因此配置如下所示:

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

SecurityPolicy.getMaxLoginAttempts() 是这样的:

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