【问题标题】:Spring Boot Application with dependency having multiple datasources具有多个数据源的依赖项的 Spring Boot 应用程序
【发布时间】:2016-10-23 12:13:15
【问题描述】:

我正在尝试创建一个 Spring Boot 应用程序,其依赖项 jar 已配置了多个数据源的 context.xml。

在我的 Spring Boot 应用程序中,我将 @ImportResource("context.xml") 添加到 @Configuration 类中,现在,我得到一个异常 “没有定义 [javax.sql.DataSource] 类型的合格 bean:预期的单个匹配 bean,但找到了 4:XXXDataSource,YYYDataSource,ZZZDataSource,aaaaDataSource”。

我阅读了有关 Spring Boot 中多个数据源的文档,但无法解决此问题。不确定如何配置我的类,因为我无法更改依赖 jar 来更改数据源的配置方式。

请帮忙!

【问题讨论】:

    标签: spring spring-boot spring-data datasource jdbctemplate


    【解决方案1】:

    您可以使用数据源 bean 上的“Primary”属性来让您的自动装配默认选择它。

    <bean primary="true|false"/>
    

    如果您使用的是 Java 配置,请改用 @Primary 注释。

    http://docs.spring.io/spring-framework/docs/4.0.4.RELEASE/javadoc-api/org/springframework/context/annotation/Primary.html

     @Component
     public class FooService {
         private FooRepository fooRepository;
    
         @Autowired
         public FooService(FooRepository fooRepository) {
             this.fooRepository = fooRepository;
         }
     }
    
     @Component
     public class JdbcFooRepository {
         public JdbcFooService(DataSource dataSource) {
             // ...
         }
     }
    
     @Primary
     @Component
     public class HibernateFooRepository {
         public HibernateFooService(SessionFactory sessionFactory) {
             // ...
         }
     }
    

    如果这仍然不能解决问题,您可以命名 bean,并在您的 java 类中使用 @Qualifier 注解,或者在您的 Spring XML 配置中使用“ref”属性。

    https://spring.io/blog/2014/11/04/a-quality-qualifier

    @Autowired 
    @Qualifier( "ios") // the use is unique to Spring. It's darned convenient, too!
    private MarketPlace marketPlace ;  
    

    如果您需要jar中的数据源之一并且无法修改配置,而不是从jar中导入xml,请将您需要的配置复制到您自己的本地spring上下文配置中。

    【讨论】:

    • 添加到依赖 jar 的 context.xml 中的数据源 bean 之一就可以了!非常感谢!!!!!!!
    猜你喜欢
    • 2018-01-28
    • 2021-01-01
    • 1970-01-01
    • 2018-10-07
    • 2015-07-10
    • 2018-08-29
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    相关资源
    最近更新 更多