当前位置: 首页 > 知识库问答 >
问题:

多个数据源和多个配置文件

芮明知
2023-03-14

我有两个配置文件(“autoContido”和“weblogic”),其中每个配置文件都有两个配置类,因为我使用的是两个数据源。

我已经将特定数据源中的bean注释为@Primary,而另一个数据源配置类中的bean不是@Primary,但我对它们的命名不同。

我以为使用@主注释就不会有像下面这样的错误,但我仍然得到它们。有人能帮我看看问题出在哪里吗?

"Parameter 0 of constructor in br.com.brb.maf.model.repository.impl.EmprestimoTelebancoRepositoryImpl required a single bean, but 2 were found:
    - org.springframework.orm.jpa.SharedEntityManagerCreator#0: defined by method 'createSharedEntityManager' in null
    - org.springframework.orm.jpa.SharedEntityManagerCreator#1: defined by method 'createSharedEntityManager' in null"

我尝试使用@Primary annotation,但仍在br中获取构造函数的错误参数0。通用域名格式。brb。maf公司。模型存储库。实施。EmprestimoTelebancoRepositoryImpl需要一个bean,但找到了2个

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        basePackages = {"br.com.brb.maf.model.pesquisa.repository"},
        transactionManagerRef = "customMobileTransactionManager",
        entityManagerFactoryRef = "mobileEntityManager")
@Profile("weblogic")
public class BanknetDatabaseConfiguration implements EnvironmentAware {

 //ommited ...

@Value("${spring.datasource.mobile.jndi-name}")
    private String mobileJndiName;

    @Override
    public void setEnvironment(Environment environment) {
        this.jpaPropertyResolver = new RelaxedPropertyResolver(environment, SPRING_JPA_PROPERTIES);
        this.dataSourcePropertyResolver = new RelaxedPropertyResolver(environment, SPRING_DATASOURCE);
    }

    @Bean(name = "customMobileTransactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("mobileEntityManager") EntityManagerFactory emf) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);
        return transactionManager;
    }

    @Bean(name = "mobileDataSource")
    public DataSource dataSource() {
        final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
        dsLookup.setResourceRef(true);
        DataSource dataSource = dsLookup.getDataSource(mobileJndiName);
        return dataSource;
    }

    @Bean(name = "mobileEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(
            @Qualifier("mobileDatasource") DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource);
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());
        em.setPackagesToScan(new String[] {"br.com.brb.maf.model.pesquisa"});

        return em;
    }

    Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty(HIBERNATE_HBM2DDL_AUTO,
                jpaPropertyResolver.getProperty(HIBERNATE_HBM2DDL_AUTO, VALIDATE));
        properties.setProperty(HIBERNATE_DIALECT, jpaPropertyResolver.getProperty(HIBERNATE_DIALECT));
        properties.setProperty(HIBERNATE_DEFAULT_SCHEMA, jpaPropertyResolver.getProperty(HIBERNATE_DEFAULT_SCHEMA));
        properties.setProperty(HIBERNATE_SHOW_SQL,
                jpaPropertyResolver.getProperty(HIBERNATE_SHOW_SQL, Boolean.FALSE.toString()));
        properties.setProperty(HIBERNATE_FORMAT_SQL,
                jpaPropertyResolver.getProperty(HIBERNATE_FORMAT_SQL, Boolean.FALSE.toString()));
        return properties;
    }
}
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        basePackages = {"br.com.brb.maf.model.repository"},
        transactionManagerRef = "customTransactionManager",
        entityManagerFactoryRef = "entityManagerFactory")
@Profile("weblogic")
public class DatabaseConfiguration implements EnvironmentAware {

//ommited...

@Value("${spring.datasource.maf.jndi-name}")
    private String mafJndiName;

    @Override
    public void setEnvironment(Environment environment) {
        this.jpaPropertyResolver = new RelaxedPropertyResolver(environment, SPRING_JPA_PROPERTIES);
        this.dataSourcePropertyResolver = new RelaxedPropertyResolver(environment, SPRING_DATASOURCE);
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(
            @Qualifier("dataSource") DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource);
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());
        em.setPackagesToScan(new String[] {"br.com.brb.maf.model"});

        return em;
    }

    @Primary
    @Bean(name = "dataSource")
    public DataSource dataSource() {
        final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
        dsLookup.setResourceRef(true);
        // DataSource dataSource =
        // dsLookup.getDataSource(dataSourcePropertyResolver.getProperty(JNDI_NAME));
        DataSource dataSource = dsLookup.getDataSource(mafJndiName);
        return dataSource;
    }

    @Primary
    @Bean(name = "customTransactionManager")
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);
        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty(HIBERNATE_HBM2DDL_AUTO,
                jpaPropertyResolver.getProperty(HIBERNATE_HBM2DDL_AUTO, VALIDATE));
        properties.setProperty(HIBERNATE_DIALECT, jpaPropertyResolver.getProperty(HIBERNATE_DIALECT));
        properties.setProperty(HIBERNATE_DEFAULT_SCHEMA, jpaPropertyResolver.getProperty(HIBERNATE_DEFAULT_SCHEMA));
        properties.setProperty(HIBERNATE_SHOW_SQL,
                jpaPropertyResolver.getProperty(HIBERNATE_SHOW_SQL, Boolean.FALSE.toString()));
        properties.setProperty(HIBERNATE_FORMAT_SQL,
                jpaPropertyResolver.getProperty(HIBERNATE_FORMAT_SQL, Boolean.FALSE.toString()));
        return properties;
    }
}
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        basePackages = { "br.com.brb.maf.model.pesquisa.repository" })
@Profile("autoContido")
public class BanknetDatabaseConfigurationStandalone implements EnvironmentAware {

//ommited...

@Override
    public void setEnvironment(Environment environment) {
        this.jpaPropertyResolver = new RelaxedPropertyResolver(environment, SPRING_JPA_PROPERTIES);
        new RelaxedPropertyResolver(environment, SPRING_DATASOURCE);
    }

    @Bean(name = "mobileDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.mobile")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "mobileEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(
            @Qualifier("mobileDataSource") DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource);
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());
        em.setPackagesToScan(new String[] {"br.com.brb.maf.model.pesquisa"});

        return em;
    }

    Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty(HIBERNATE_HBM2DDL_AUTO,
                jpaPropertyResolver.getProperty(HIBERNATE_HBM2DDL_AUTO, VALIDATE));
        properties.setProperty(HIBERNATE_DIALECT, jpaPropertyResolver.getProperty(HIBERNATE_DIALECT));
        properties.setProperty(HIBERNATE_DEFAULT_SCHEMA, jpaPropertyResolver.getProperty(HIBERNATE_DEFAULT_SCHEMA));
        properties.setProperty(HIBERNATE_SHOW_SQL,
                jpaPropertyResolver.getProperty(HIBERNATE_SHOW_SQL, Boolean.FALSE.toString()));
        properties.setProperty(HIBERNATE_FORMAT_SQL,
                jpaPropertyResolver.getProperty(HIBERNATE_FORMAT_SQL, Boolean.FALSE.toString()));
        return properties;
    }
}
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        basePackages = { "br.com.brb.maf.model.repository" })
@Profile("autoContido")
public class DatabaseConfigurationStandalone implements EnvironmentAware {

//ommited...

    @Override
    public void setEnvironment(Environment environment) {
        this.jpaPropertyResolver = new RelaxedPropertyResolver(environment, SPRING_JPA_PROPERTIES);
        new RelaxedPropertyResolver(environment, SPRING_DATASOURCE);
    }

    @Primary
    @Bean(name = "dataSource")
    @ConfigurationProperties(prefix = "spring.datasource.maf")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(
            @Qualifier("dataSource") DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource);
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());
        em.setPackagesToScan(new String[] {"br.com.brb.maf.model"});

        return em;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty(HIBERNATE_HBM2DDL_AUTO,
                jpaPropertyResolver.getProperty(HIBERNATE_HBM2DDL_AUTO, VALIDATE));
        properties.setProperty(HIBERNATE_DIALECT, jpaPropertyResolver.getProperty(HIBERNATE_DIALECT));
        properties.setProperty(HIBERNATE_DEFAULT_SCHEMA, jpaPropertyResolver.getProperty(HIBERNATE_DEFAULT_SCHEMA));
        properties.setProperty(HIBERNATE_SHOW_SQL,
                jpaPropertyResolver.getProperty(HIBERNATE_SHOW_SQL, Boolean.FALSE.toString()));
        properties.setProperty(HIBERNATE_FORMAT_SQL,
                jpaPropertyResolver.getProperty(HIBERNATE_FORMAT_SQL, Boolean.FALSE.toString()));
        return properties;
    }
}
@Repository
public class EmprestimoBanknetRepositoryImpl implements EmprestimoBanknetRepositoryCustom {

    private EntityManager entityManager;

    @Autowired
    public EmprestimoBanknetRepositoryImpl(EntityManager manager) {
        this.entityManager = manager;
    }

    @Override
    public LocalDateTime ultimaDataPesquisa() {
        String jpql = "Select distinct max(i.dataOcorrencia) from IndicioEmprestimoBanknet i ";
        Query query = entityManager.createQuery(jpql);
        return (LocalDateTime) query.getSingleResult();
    }

}

错误:

15165 [main] WARN  o.s.b.c.e.AnnotationConfigEmbeddedWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'emprestimoJobTelebancoScheduler': Unsatisfied dependency expressed through field 'telebancoJob'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'EmprestimoTelebancoJob' defined in class path resource [br/com/brb/maf/application/batch/emprestimo/telebanco/EmprestimoTelebancoConfiguration.class]: Unsatisfied dependency expressed through method 'emprestimoTelebancoJob' parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'EmprestimoTelebancoJobStep' defined in class path resource [br/com/brb/maf/application/batch/emprestimo/telebanco/EmprestimoTelebancoConfiguration.class]: Unsatisfied dependency expressed through method 'step' parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'emprestimoTelebancoReader': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'emprestimoServiceImpl': Unsatisfied dependency expressed through field 'telebancoRepository'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'emprestimoTelebancoRepositoryImpl' defined in file [C:\Users\u840280\Desktop\SVN\MAF\backend\construcao\branches\DSV_1.0.7\fontes\target\classes\br\com\brb\maf\model\repository\impl\EmprestimoTelebancoRepositoryImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManager' available: expected single matching bean but found 2: org.springframework.orm.jpa.SharedEntityManagerCreator#0,org.springframework.orm.jpa.SharedEntityManagerCreator#1 
15181 [main] INFO  o.s.o.j.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'default' 
15181 [main] INFO  o.s.o.j.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'default' 
15212 [main] INFO  o.s.b.a.l.AutoConfigurationReportLoggingInitializer - 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled. 
15228 [main] ERROR o.s.b.d.LoggingFailureAnalysisReporter - 

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in br.com.brb.maf.model.repository.impl.EmprestimoTelebancoRepositoryImpl required a single bean, but 2 were found:
    - org.springframework.orm.jpa.SharedEntityManagerCreator#0: defined by method 'createSharedEntityManager' in null
    - org.springframework.orm.jpa.SharedEntityManagerCreator#1: defined by method 'createSharedEntityManager' in null


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

共有2个答案

谢和颂
2023-03-14

对我来说,最突出的是,在通过EnableJpaRepositories注释定义存储库时,您没有在独立配置中定义事务和实体管理器引用,而是在标准配置中定义。

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    basePackages = { "br.com.brb.maf.model.repository" }
)
@Profile("autoContido")
public class DatabaseConfigurationStandalone implements EnvironmentAware

如果您使用的是Hibernate,那么管理器可以是同一个bean,所以只需将@Profile注释从配置移动到数据源bean即可。

以下是使用2个数据源的示例:Spring JPA-多个数据库使用多个配置文件进行此操作应该像向每个配置类添加@Profile注释一样简单,只需确保它们与其他注释相同。

冯翔
2023-03-14

我找到了答案。我只需要明确设置我将在EmoBanknetRepositoryImpl中使用哪个EnityManager。所以,最后,它必须如下所示:

@Repository
public class EmprestimoBanknetRepositoryImpl implements EmprestimoBanknetRepositoryCustom {

    private EntityManager entityManager;

    @Autowired
    public EmprestimoBanknetRepositoryImpl(@Qualifier("mobileEntityManagerFactory") EntityManager manager) {
        this.entityManager = manager;
    }

    @Override
    public LocalDateTime ultimaDataPesquisa() {
        String jpql = "Select distinct max(i.dataOcorrencia) from IndicioEmprestimoBanknet i ";
        Query query = entityManager.createQuery(jpql);
        return (LocalDateTime) query.getSingleResult();
    }

}
 类似资料:
  • 问题内容: 我正在使用Spring和Hibernate,Spring的配置如下。如何配置两个数据源, session factories。使用注释管理事务。请指教 问题答案: 在Hibernate DAO中,我们可以使用@Qualifier注释,如下所示连接2个会话工厂

  • 问题内容: 我正在使用Spring和Hibernate,Spring的配置如下。如何配置两个数据源,会话工厂。使用注释管理事务。请指教 问题答案: 在Hibernate DAO中,我们可以使用@Qualifier注释,如下所示连接2个会话工厂

  • 1-我有一个带有Spring Boot的API,我需要配置两个DBMS(MySQL和Postgres)。 2-对于每个DBMS,我需要配置不同的配置文件。(Dev,Prod) 遵循我的MySQL配置类: 我以为我的出口是: 重要: 当我将配置文件配置为连接到我的MySQL Dev数据库时,我只想连接到它。我想要同样的结果,当它是MySQL的Prod的基础时。 当我将配置文件配置为连接到我的Post

  • 如何创建具有应用程序属性中提到的多个数据源配置的单个配置 java 文件,以便在添加任意“n”个数据源时。它必须使用相同的配置文件自动处理所有数据源。 此外,所有数据源必须使用相同的 JPARepository 来查询数据。此外,我想创建一个实体管理器列表,以对特定数据源执行特定操作。 application.properties 站点配置.java 这是单个数据源配置文件的基本示例。我想以“si

  • 问题内容: 我正在尝试使用此网络研讨会中概述的单独的架构方法向Java应用程序添加多租户 我想知道如何通过spring来配置多个数据源,也许是通过使用属性文件并基于租户id从spring上下文中获取数据源。 更重要的是,尽管我希望能够配置支持此多租户功能的自定义连接提供程序实现,以供Hibernate使用,而不是默认使用的注入功能。 我怎样才能做到这一点。 问题答案: 使用。

  • 在我的项目中,我有以下db config类,其中我尝试为两个数据源之一配置多个jdbctemplate和一个命名的jdbc模板: 我似乎已经在我的yaml文件中正确配置了所有内容: 但我得到错误: <代码>组织。springframework。豆。工厂UnsatisfiedDependencyException:创建名为“somedao”的bean时出错:通过字段“namedParameterJd