java - 在运行时重新加载 spring bean

标签 java spring applicationcontext

我正在尝试在运行时更改 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/

相关文章:

java - 使用单独的 application.properties 创建 Spring Boot 测试

java - 使用 ApplicationContext 初始化 bean 时发生类转换异常

java - 了解gradle.properties和java-opts

java - 如何在自定义查询中加载@ElementCollection?

java - 如何在遵循 MVC 的 JTable 中显示 SQL 数据库中的数据?

java - 禁用 Spring Boot hello world 应用程序中的所有模块

java - 如何在 spring 应用程序上下文 xml 文件中调用带有几个参数的 java 方法

spring - 上下文初始化失败或加载属性

java - Spring webflow externalRedirect 重新启动相同的流程

Java双除正