如何以函数式方式在@RefreshScope中注册Spring Bean?

3
我有许多自己定制的“起始”项目。我正在将这些项目和其他项目迁移到Spring Boot 2.0、Framework 5.0和函数式bean定义中。
在这些“起始”项目中,我遵循的函数式bean定义模式是使用org.springframework.context.ApplicationContextInitializer。
以下是尝试在“刷新”范围内注册bean的示例配置类。
package my.package;

public class MyConfiguration implements ApplicationContextInitializer<GenericApplicationContext> {

    @Override
    public void initialize(GenericApplicationContext context) {
        context.registerBean(MyConfiguration.class);
        context.registerBean("myBean",
            MyBean.class,
            () -> new MyBeanImpl(context.getBean(MyBeanDependency.class)),
            bd -> bd.setScope("refresh"),
            bd -> bd.setLazyInit(true));
    }
}

然后,将MyConfiguration列在META-INF/spring.factories文件中,如下所示。
# context init
org.springframework.context.ApplicationContextInitializer=\
my.package.MyConfiguration

当我尝试在类路径上运行一个使用该启动器的应用程序时,我会在启动时看到异常,指示没有刷新范围。
java.lang.IllegalStateException: No Scope registered for scope name 'refresh'

我猜想这可能是一个排序问题。也就是说,在创建我的bean时,RefreshScope bean还没有被创建?org.springframework.cloud.autoconfigure.RefreshAutoConfiguration声明了RefreshScope bean。
有没有一种好的或建议的方式来功能性地注册需要在@RefreshScope中的spring beans?

1
有趣的问题,Jeff。可惜没有人回答,而且我也毫无头绪。 - LppEdd
1个回答

0
这可能会有所帮助 - 我将一个控制器标记为RefreshScope,但我遇到了以下错误 -
DEBUG org.springframework.web.servlet.DispatcherServlet - 无法完成请求 java.lang.IllegalStateException:未注册名称为'refresh'的范围
下面提到的代码片段解决了此错误。
    @DependsOn("refreshScope")
    public CustomScopeConfigurer servletCustomScopeConfigurer(RefreshScope refreshScope) {
        CustomScopeConfigurer customScopeConfigurer = new CustomScopeConfigurer();
        customScopeConfigurer.addScope("refresh", refreshScope);
        return customScopeConfigurer;
    }

    @Bean
    public RefreshScope refreshScope(){
        return new RefreshScope();
    }

Ref: https://github.com/spring-cloud/spring-cloud-config/issues/1116


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接