如何在不使用@Primary注释的情况下管理两个数据源?

时间:2017-03-15 11:16:37

标签: java spring-boot

我有两个数据源

  1. Quartz
  2. 简单JPA
  3. 我希望他们都住在同一个基于Spring的Web应用程序中, 所以我创建了两个类:

    1

    @Configuration
    
    
    public class QuartzDataSource {
    
    @Bean
    // @Primary
    @Qualifier("quartzDataSourceProperties")
    @ConfigurationProperties(prefix="org.quartz.dataSource")
    public DataSourceProperties quartzDataSourceProperties() {
        DataSourceProperties dataSourceProperties = new DataSourceProperties();
        return dataSourceProperties;
    }
    
    @Bean
    //   @Primary
    @Qualifier("quartzDataSource")
    @ConfigurationProperties(prefix="org.quartz.dataSource")
    public DataSource quartzdataSource( @Qualifier("quartzDataSourceProperties") DataSourceProperties dataSourceProperties) {
        DataSource build = dataSourceProperties.initializeDataSourceBuilder().build();
        return build;
        }
    }
    

    2

    @Configuration
    @EnableTransactionManagement
    @EnableAutoConfiguration
    @EnableJpaRepositories(
        entityManagerFactoryRef = "JPAEntityManager",
        transactionManagerRef = "JPATransactionManager",
        basePackages = {"com.schedulerservice"})
    public class JpaDataSourceConfiguration {
    
    
    @Bean
    @Qualifier("taskStatusDataSourceProperties")
    @ConfigurationProperties("task.status.datasource")
    public DataSourceProperties dataSourceProperties() {
        DataSourceProperties dataSourceProperties = new DataSourceProperties();
        return dataSourceProperties;
    }
    
    @Bean
    @Qualifier("taskStatusDataSource")
    @ConfigurationProperties("task.status.datasource")
    public DataSource taskStatusDataSource(@Qualifier("taskStatusDataSourceProperties") DataSourceProperties dataSourceProperties) {
        return dataSourceProperties.initializeDataSourceBuilder().build();
       }
    
    }
    

    我试过了应用程序

      @EnableAutoConfiguration(exclude = {
        EndpointWebMvcAutoConfiguration.class,
       DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
    

    但没有成功,我得到的错误是

    Parameter 0 of method dataSourceInitializer in org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration required a single bean, but 3 were found:
    - dataSourceProperties: defined by method 'dataSourceProperties' in class path resource [com/schedulerservice/configuration/JpaDataSourceConfiguration.class]
    - quartzDataSourceProperties: defined by method 'quartzDataSourceProperties' in class path resource [com/schedulerservice/configuration/quartz/QuartzDataSource.class]
    - spring.datasource-org.springframework.boot.autoconfigure.jdbc.DataSourceProperties: defined in null
    

    当我添加@Primary annotation时,一切正常

    如何避免使用@Primary注释?

0 个答案:

没有答案