首页 > 其他 > 详细

使用@ConditionalOnProperty遇到的错误

时间:2020-12-23 12:48:18      阅读:393      评论:0      收藏:0      [点我收藏+]

前提

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

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注解属性配置错误。

  • value别名。

  • prefix属性的前缀。 如果未指定,前缀会自动以.(圆点符号)结尾。 一个有效的前缀由一个或多个用点分隔的单词定义(例如: acme.system.feature)。

  • name要测试的属性的名称。 如果已定义前缀,则将其用于计算每个属性的完整键。 例如,如果前缀为 app.config,而一个值为 my-value,则全键为 app.config.my-value。使用-(短横线连接符)分隔单词,例如:my-long-property

  • havingValue属性期望值的字符串表示形式。如果属性根本不包含在 Environment 中,则会查询 matchIfMissing ()属性。 缺省情况下,缺少的属性不匹配。此条件无法可靠地用于匹配集合属性。

  • matchIfMissing如果未设置属性,条件是否应匹配。 默认为false。


将注解改为以下形式:

@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

使用@ConditionalOnProperty遇到的错误

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!