source

Spring Boot Multiple Database : EntityManagerFactoryBuilder 유형의 한정된 빈 없음

factcode 2023. 9. 6. 22:23
반응형

Spring Boot Multiple Database : EntityManagerFactoryBuilder 유형의 한정된 빈 없음

Spring Boot Application에는 source와 target이라는 두 개의 데이터베이스가 있습니다.이것은 그것들을 위한 구성입니다.

소스 구성

package com.alex.myapp.config;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "sourceManagerFactory",
        transactionManagerRef = "sourceTransactionManager",
        basePackages = {"com.alex.myapp.source.repository"}
)
public class SourceDbConfiguration {

    @Autowired
    private Environment env;

    @Primary
    @Bean(name = "sourceManagerFactory")
    public LocalContainerEntityManagerFactoryBean
    sourceManagerFactory(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean em = builder
                .dataSource(sourceDataSource())
                .packages("com.alex.myapp.source.entity")
                .persistenceUnit("source")
                .build();
        return em;
    }

    @Primary
    @Bean
    public DataSource sourceDataSource() {
        DriverManagerDataSource dataSource
                = new DriverManagerDataSource();
        dataSource.setDriverClassName(
                env.getProperty("spring.datasource.driver-class-name"));
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));

        return dataSource;
    }

    @Primary
    @Bean(name = "sourceTransactionManager")
    public PlatformTransactionManager sourceTransactionManager(
            @Qualifier("sourceManagerFactory") EntityManagerFactory
                    sourceManagerFactory
    ) {
        return new JpaTransactionManager(sourceManagerFactory);
    }
}

대상 구성

package com.alex.myapp.config;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "targetManagerFactory",
        transactionManagerRef = "targetTransactionManager",
        basePackages = {"com.alex.myapp.target.repository"}
)
public class TargetDbConfiguration {

    @Autowired
    private Environment env;

    @Primary
    @Bean(name = "targetManagerFactory")
    public LocalContainerEntityManagerFactoryBean
    targetManagerFactory(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean em = builder
                .dataSource(targetDataSource())
                .packages("com.alex.myapp.target.entity")
                .persistenceUnit("target")
                .build();
        return em;
    }

    @Primary
    @Bean
    public DataSource targetDataSource() {
        DriverManagerDataSource dataSource
                = new DriverManagerDataSource();
        dataSource.setDriverClassName(
                env.getProperty("target.datasource.driver-class-name"));
        dataSource.setUrl(env.getProperty("target.datasource.url"));
        dataSource.setUsername(env.getProperty("target.datasource.username"));
        dataSource.setPassword(env.getProperty("target.datasource.password"));

        return dataSource;
    }

    @Bean(name = "targetTransactionManager")
    public PlatformTransactionManager targetTransactionManager(
            @Qualifier("targetManagerFactory") EntityManagerFactory
                    targetManagerFactory) {
        return new JpaTransactionManager(targetManagerFactory);
    }
}

서버를 시작하려고 하면 아래에 언급된 오류가 발생합니다.

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-09-19 13:30:53 - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sourceManagerFactory' defined in class path resource [com/alex/myapp/config/SourceDbConfiguration.class]: Unsatisfied dependency expressed through method 'sourceManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:732)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:474)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1247)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1096)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:859)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)

내가 target configuration의 class level 주석을 주석으로 달면 jut는 모든 것이 잘 작동합니다.두 데이터베이스 구성이 서로 충돌하는 것 같습니다.

@Primary필수 유형 중에서 한 콩에 정확하게 사용해야 합니다.

@Primary javadoc에서 추출

여러 후보가 단일 값 종속성을 자동으로 할당할 수 있는 자격이 있는 경우 빈에 우선 순위를 부여해야 함을 나타냅니다.후보들 사이에 정확히 하나의 '1차' 빈이 존재할 경우 자동 배선 값이 됩니다.

코드에 오류가 있습니다.지정합니다.

@Primary 

두 데이터 소스 모두에 대한 주석이므로 Spring이 주장합니다.따라서 이 주석을 수업 중 하나에서 제거해야 하며 모든 것이 괜찮을 것입니다.

또한 이름을 지정하지 않고 트랜잭션 관리자를 암묵적으로 또는 명시적으로 주입할 때 주 주석이 도움이 됩니다.

언급URL : https://stackoverflow.com/questions/52401041/spring-boot-multiple-databse-no-qualifying-bean-of-type-entitymanagerfactorybu

반응형