使用@ConditionalOnProperty遇到的错误

时间:2020-12-23 12:48:18   收藏:0   阅读:393

前提

在配置多数据源时报错,错误如下所示:

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

提示程序上下文中某些Bean的依赖性形成一个循环,猜测可能是使用@ConditionalOnProperty注解有条件的注册Bean时出现的问题。

@conditionalonproperty 仅在存在环境属性中具有特定值的情况下才启用 bean 注册。


配置文件:

spring:
  datasource:
    local:
      jdbc-url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true@characterEncoding=utf-8
      username: root
      password: 123
      driver-class-name: com.mysql.cj.jdbc.Driver
    remote:
      jdbc-url: jdbc:mysql://192.168.1.200:3306/test?serverTimezone=UTC&useUnicode=true@characterEncoding=utf-8
      username: root
      password: 123
      driver-class-name: com.mysql.cj.jdbc.Driver

注入数据源:

@Configuration
@ConditionalOnClass(DataSource.class)			// 必须存在的类
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)		// 允许在自动配置类之间进行排序,只会影响其Bean的定义顺序
@PropertySource("classpath:application.yml")	
public class DataSourceConfig {

    @Bean
    @ConditionalOnProperty(prefix = "spring.datasource", name = "remote")	// 根据配置的属性值有条件地创建bean
    @ConditionalOnMissingBean							// 如果BeanFactory中没有包含DataSource类型的Bean,则进行条件匹配
    public DataSource remoteDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConditionalOnProperty(prefix = "spring.datasource", name = "local")
    @ConditionalOnMissingBean(name = "localDataSource")
    public DataSource localDataSource() {
        return DataSourceBuilder.create().build();
    }
}

方法

查询官网后发现@ConditionalOnProperty注解属性配置错误。


将注解改为以下形式:

@ConditionalOnProperty(prefix = "spring.datasource.remote", name = "jdbc-url")	// name随意测试一个属性即可,即username、password等
// 或者
@ConditionalOnProperty(prefix = "spring.datasource", name = "local", matchIfMissing = true)

参考

https://www.baeldung.com/spring-conditionalonproperty
https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/condition/ConditionalOnProperty.html

原文:https://www.cnblogs.com/Ming-Yi/p/14177861.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!