在@Configuration或@SpringBootApplication上使用@RefreshScope无法解析的循环引用

时间:2018-08-19 17:36:19

标签: spring spring-boot spring-cloud spring-cloud-config

在修改属性并请求apiKey端点之后,我试图获取属性/refresh的刷新值。

由于某种原因,即使使用@RefreshScope进行注释,我的bean也无法获得刷新的值。我在课堂上添加了@RefreshScope,就像为DatasourceConfig做的那样,但是在这种情况下,我遇到了这个错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.application': Initialization of bean failed;

nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.application.initTimestamp.transformer.handler': Invocation of init method failed;

nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'scopedTarget.application': Requested bean is currently in creation: Is there an unresolvable circular reference?

Description:

The dependencies of some of the beans in the application context form a cycle:

┌─────┐
|  scopedTarget.application
└─────┘

这是我的Application.java

@SpringBootApplication
@EnableConfigServer
@EnableSwagger2
@RefreshScope
public class Application{

    @Value("${api.key}")
    private String apiKey;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Autowired
    private IMonitoringsService monitoringsService;

    @Bean
    public MessageChannel initTimestampChannel() {
        return new DirectChannel();
    }

    @RefreshScope
    @Bean
    @InboundChannelAdapter(value = "initTimestampChannel", poller = @Poller(fixedRate = "${start.task.rate}"))
    public MessageSource<?> buildRequestMessageSource() {
        MethodInvokingMessageSource source = new MethodInvokingMessageSource();
        source.setObject(tasksService);
        source.setMethodName("requestAllTasks");
        System.out.println(apiKey);
        return source;
    }

}

但是它正在为我的DatasourceConfig工作:

@RefreshScope
@Configuration
public class DatasourceConfig {
    @Value("${spring.datasource.tomcat.max-active}")
    private int maxActive;

    @RefreshScope
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource dataSource() {
        DataSource dataSource = DataSourceBuilder.create().build();
        org.apache.tomcat.jdbc.pool.DataSource ds = (org.apache.tomcat.jdbc.pool.DataSource) dataSource;
        ds.setMaxActive(maxActive);
        return ds;
    }
}

我正在使用:

<spring-cloud.version>Edgware.SR2</spring-cloud.version>
<spring-boot-version>1.5.9.RELEASE</spring-boot-version>

1 个答案:

答案 0 :(得分:0)

正如spencergibb建议的那样,您不应将::@SpringBootApplication放在同一个班级。从@RefreshScope中删除@RefreshScope,并将需要Application的配置移到单独的类中。