gpt4 book ai didi

java - Spring Data Autowiring 多个数据源失败

转载 作者:行者123 更新时间:2023-11-29 22:10:12 24 4
gpt4 key购买 nike

我一直在努力尝试将多个 mysql 数据源放入 Spring jpa 应用程序中,似乎永远如此。我还没有在网上找到一个好的、有效的例子。下面是我制作的一个极其精简的应用程序的摘录,只是为了看看是否有可能在真空中自动连接和查询多个 MySQL 数据库的存储库。无论我输入或输出什么注释都没有任何变化,我总是得到相同的错误:

Error creating bean with name 'application': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.download.integration.repository.primary.PrimaryRepository com.download.Application.PrimaryRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.download.integration.repository.primary.PrimaryRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

这是我的设置。根据之前回答的几个项目的建议,主要和次要 bean 以及存储库都位于自己的包中。

第一个配置:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "primaryEntityManagerFactory",
transactionManagerRef = "primaryTransactionManager",
basePackages = { "com.download.integration.repositories.primary" })
public class PrimaryConfig{

@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter adaptor = new HibernateJpaVendorAdapter();
adaptor.setShowSql(false);
adaptor.setGenerateDdl(false);
adaptor.setDatabase(Database.MYSQL);
return adaptor;
}


@Primary
@Bean(name = "primaryDataSource")
public DataSource primaryDataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://127.0.0.1:3306/primarydb");
ds.setUsername("user");
ds.setPassword("password");
return ds;
}

@Bean(name = "primaryEntityManager")
public EntityManager primaryEntityManager() {
return primaryEntityManagerFactory().createEntityManager();
}

@Bean(name = "primaryEntityManagerFactory")
public EntityManagerFactory primaryEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
lef.setDataSource(primaryDataSource());
lef.setJpaVendorAdapter(jpaVendorAdapter());
lef.setPackagesToScan("com.download.domain.primary");
lef.setPersistenceUnitName("primaryPersistenceUnit");
lef.afterPropertiesSet();
return lef.getObject();
}

@Bean(name = "primaryTransactionManager")
public PlatformTransactionManager primaryTransactionManager() {
return new JpaTransactionManager(primaryEntityManagerFactory());
}

}

辅助配置:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "secondaryEntityManagerFactory",
transactionManagerRef = "secondaryTransactionManager",
basePackages = { "com.download.integration.repositories.secondary" })
public class SecondaryConfig{

@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter adaptor = new HibernateJpaVendorAdapter();
adaptor.setShowSql(false);
adaptor.setGenerateDdl(false);
adaptor.setDatabase(Database.MYSQL);
return adaptor;
}

@Bean(name = "secondaryDataSource")
public DataSource secondaryDataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://127.0.0.1:3306/secondarydb");
ds.setUsername("user");
ds.setPassword("password");
return ds;
}

@Bean(name = "secondaryEntityManager")
public EntityManager secondaryEntityManager() {
return secondaryEntityManagerFactory().createEntityManager();
}

@Bean(name = "secondaryEntityManagerFactory")
public EntityManagerFactory secondaryEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
lef.setDataSource(secondaryDataSource());
lef.setJpaVendorAdapter(jpaVendorAdapter());
lef.setPackagesToScan("com.download.domain.secondary");
lef.setPersistenceUnitName("secondaryPersistenceUnit");
lef.afterPropertiesSet();
return lef.getObject();
}

@Bean(name = "secondaryTransactionManager")
public PlatformTransactionManager secondaryTransactionManager() {
return new JpaTransactionManager(secondaryEntityManagerFactory());
}

}

主要数据源模型:

@Entity
public class Primary {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String word;
private Double weight;
private Date updated;
private String sources;

...构造函数、getter、setter

辅助数据源模型:

@Entity
public class Secondary {

@Id
private String uuid;
private String name;
private Double weight;

...构造函数、getter、setter

和存储库(我尝试添加@Repository,但没有看到任何变化)

public interface PrimaryRepository extends CrudRepository<Primary, Integer> {
}

public interface SecondaryRepository extends CrudRepository<Secondary, Integer> {
}

最后是主类:

@ComponentScan("com.download")
@EnableAutoConfiguration(exclude = { DataSourceTransactionManagerAutoConfiguration.class, DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
@Import({PrimaryConfig.class, SecondaryConfig.class})
public class Application implements CommandLineRunner{

@Autowired
PrimaryRepository primaryrepository;
@Autowired
SecondaryRepository secondaryrepository;

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@Override
public void run(String... args) throws Exception {

search();

}

public void search(){
primaryrepository.findAll();
secondaryrepository.findAll();
}

}

为每个请求添加完整的堆栈跟踪:

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'application': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.download.integration.repository.primary.PrimaryRepository com.download.Application.PrimaryRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.download.integration.repository.primary.PrimaryRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at com.download.Application.main(Application.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.boot.maven.RunMojo$LaunchRunner.run(RunMojo.java:418)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.download.integration.repository.primary.PrimaryRepository com.download.Application.PrimaryRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.download.integration.repository.primary.PrimaryRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 21 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.download.integration.repository.primary.PrimaryRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 23 common frames omitted

2015-07-31 17:39:22.028 INFO 26516 --- [lication.main()] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2015-07-31 17:39:22.029 INFO 26516 --- [lication.main()] .b.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/Users/cora/multiDatasourceTest/src/main/resources, file:/Users/cora/multiDatasourceTest/src/main/resources, file:/Users/cora/multiDatasourceTest/target/classes/, file:/Users/cora/.m2/repository/org/aspectj/aspectjweaver/1.8.5/aspectjweaver-1.8.5.jar, file:/Users/cora/.m2/repository/org/springframework/boot/spring-boot-starter-aop/1.2.4.RELEASE/spring-boot-starter-aop-1.2.4.RELEASE.jar, file:/Users/cora/.m2/repository/org/springframework/spring-core/4.1.6.RELEASE/spring-core-4.1.6.RELEASE.jar, file:/Users/cora/.m2/repository/org/springframework/boot/spring-boot-starter-jdbc/1.2.4.RELEASE/spring-boot-starter-jdbc-1.2.4.RELEASE.jar, file:/Users/cora/.m2/repository/org/springframework/spring-context/4.1.6.RELEASE/spring-context-4.1.6.RELEASE.jar, file:/Users/cora/.m2/repository/org/yaml/snakeyaml/1.14/snakeyaml-1.14.jar, file:/Users/cora/.m2/repository/aopalliance/aopalliance/1.0/aopalliance-1.0.jar, file:/Users/cora/.m2/repository/org/hibernate/hibernate-entitymanager/5.0.0.CR3/hibernate-entitymanager-5.0.0.CR3.jar, file:/Users/cora/.m2/repository/org/springframework/boot/spring-boot/1.2.4.RELEASE/spring-boot-1.2.4.RELEASE.jar, file:/Users/cora/.m2/repository/org/springframework/spring-jdbc/4.1.6.RELEASE/spring-jdbc-4.1.6.RELEASE.jar, file:/Users/cora/.m2/repository/org/springframework/spring-orm/4.1.6.RELEASE/spring-orm-4.1.6.RELEASE.jar, file:/Users/cora/.m2/repository/org/springframework/boot/spring-boot-starter/1.2.4.RELEASE/spring-boot-starter-1.2.4.RELEASE.jar, file:/Users/cora/.m2/repository/ch/qos/logback/logback-core/1.1.3/logback-core-1.1.3.jar, file:/Users/cora/.m2/repository/org/springframework/data/spring-data-jpa/1.7.2.RELEASE/spring-data-jpa-1.7.2.RELEASE.jar, file:/Users/cora/.m2/repository/org/springframework/boot/spring-boot-starter-logging/1.2.4.RELEASE/spring-boot-starter-logging-1.2.4.RELEASE.jar, file:/Users/cora/.m2/repository/org/slf4j/slf4j-api/1.7.12/slf4j-api-1.7.12.jar, file:/Users/cora/.m2/repository/org/springframework/spring-aspects/4.1.6.RELEASE/spring-aspects-4.1.6.RELEASE.jar, file:/Users/cora/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar, file:/Users/cora/.m2/repository/org/slf4j/jul-to-slf4j/1.7.12/jul-to-slf4j-1.7.12.jar, file:/Users/cora/.m2/repository/commons-pool/commons-pool/1.6/commons-pool-1.6.jar, file:/Users/cora/.m2/repository/xml-apis/xml-apis/1.0.b2/xml-apis-1.0.b2.jar, file:/Users/cora/.m2/repository/org/apache/tomcat/tomcat-juli/8.0.23/tomcat-juli-8.0.23.jar, file:/Users/cora/.m2/repository/org/springframework/spring-beans/4.1.6.RELEASE/spring-beans-4.1.6.RELEASE.jar, file:/Users/cora/.m2/repository/org/springframework/data/spring-data-commons/1.9.2.RELEASE/spring-data-commons-1.9.2.RELEASE.jar, file:/Users/cora/.m2/repository/org/slf4j/jcl-over-slf4j/1.7.12/jcl-over-slf4j-1.7.12.jar, file:/Users/cora/.m2/repository/antlr/antlr/2.7.7/antlr-2.7.7.jar, file:/Users/cora/.m2/repository/org/apache/tomcat/tomcat-jdbc/8.0.23/tomcat-jdbc-8.0.23.jar, file:/Users/cora/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/1.2.4.RELEASE/spring-boot-autoconfigure-1.2.4.RELEASE.jar, file:/Users/cora/.m2/repository/org/javassist/javassist/3.18.1-GA/javassist-3.18.1-GA.jar, file:/Users/cora/.m2/repository/ch/qos/logback/logback-classic/1.1.3/logback-classic-1.1.3.jar, file:/Users/cora/.m2/repository/org/hibernate/hibernate-core/5.0.0.CR3/hibernate-core-5.0.0.CR3.jar, file:/Users/cora/.m2/repository/org/apache/geronimo/specs/geronimo-jta_1.1_spec/1.1.1/geronimo-jta_1.1_spec-1.1.1.jar, file:/Users/cora/.m2/repository/org/hibernate/common/hibernate-commons-annotations/5.0.0.Final/hibernate-commons-annotations-5.0.0.Final.jar, file:/Users/cora/.m2/repository/org/aspectj/aspectjrt/1.8.5/aspectjrt-1.8.5.jar, file:/Users/cora/.m2/repository/org/slf4j/log4j-over-slf4j/1.7.12/log4j-over-slf4j-1.7.12.jar, file:/Users/cora/.m2/repository/commons-dbcp/commons-dbcp/1.4/commons-dbcp-1.4.jar, file:/Users/cora/.m2/repository/org/springframework/spring-expression/4.1.6.RELEASE/spring-expression-4.1.6.RELEASE.jar, file:/Users/cora/.m2/repository/org/springframework/spring-tx/4.1.6.RELEASE/spring-tx-4.1.6.RELEASE.jar, file:/Users/cora/.m2/repository/org/jboss/jandex/1.2.2.Final/jandex-1.2.2.Final.jar, file:/Users/cora/.m2/repository/javax/transaction/javax.transaction-api/1.2/javax.transaction-api-1.2.jar, file:/Users/cora/.m2/repository/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar, file:/Users/cora/.m2/repository/org/springframework/boot/spring-boot-starter-data-jpa/1.2.4.RELEASE/spring-boot-starter-data-jpa-1.2.4.RELEASE.jar, file:/Users/cora/.m2/repository/org/jboss/logging/jboss-logging/3.3.0.Final/jboss-logging-3.3.0.Final.jar, file:/Users/cora/.m2/repository/org/springframework/spring-aop/4.1.6.RELEASE/spring-aop-4.1.6.RELEASE.jar]
2015-07-31 17:39:22.030 INFO 26516 --- [lication.main()] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report enable debug logging (start with --debug)


2015-07-31 17:39:22.031 ERROR 26516 --- [lication.main()] o.s.boot.SpringApplication : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'application': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.download.integration.repository.primary.PrimaryRepository com.download.Application.PrimaryRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.download.integration.repository.primary.PrimaryRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at com.download.Application.main(Application.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.boot.maven.RunMojo$LaunchRunner.run(RunMojo.java:418)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.download.integration.repository.primary.PrimaryRepository com.download.Application.PrimaryRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.download.integration.repository.primary.PrimaryRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 21 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.download.integration.repository.primary.PrimaryRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 23 common frames omitted

[WARNING]
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.boot.maven.RunMojo$LaunchRunner.run(RunMojo.java:418)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'application': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.download.integration.repository.primary.PrimaryRepository com.download.Application.PrimaryRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.download.integration.repository.primary.PrimaryRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at com.download.Application.main(Application.java:32)
... 6 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.download.integration.repository.primary.PrimaryRepository com.download.Application.PrimaryRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.download.integration.repository.primary.PrimaryRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 21 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.download.integration.repository.primary.PrimaryRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 23 more

最佳答案

为了简单起见,您可以删除 @Import 并放置 @EnableAutoConfiguration 而不使用 exclude 字段。另外,尝试将 @Configuration 添加到您的主类中。

编辑:

我已经使用您的类创建了一个项目,并在以下更改后工作:

1 Application.java

@ComponentScan("com.download")
@EnableAutoConfiguration
public class Application implements CommandLineRunner {

@Autowired
PrimaryRepository primaryrepository;
@Autowired
SecondaryRepository secondaryrepository;

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@Override
public void run(String... args) throws Exception {

search();

}

public void search() {
primaryrepository.findAll();
secondaryrepository.findAll();
}

}

2 PrimaryConfig.java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "primaryEntityManager", transactionManagerRef = "primaryTransactionManager",
basePackages = {"com.download.integration.repositories.primary"})
public class PrimaryConfig {

@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter adaptor = new HibernateJpaVendorAdapter();
adaptor.setShowSql(false);
adaptor.setGenerateDdl(false);
adaptor.setDatabase(Database.MYSQL);
return adaptor;
}

@Primary
@Bean(name = "primaryDataSource")
public DataSource primaryDataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://127.0.0.1:3306/primarydb");
ds.setUsername("user");
ds.setPassword("password");
return ds;
}

@Bean
public LocalContainerEntityManagerFactoryBean primaryEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(primaryDataSource());
em.setPackagesToScan(new String[] {"com.download.domain.primary"});

HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("hibernate.hbm2ddl.auto", "validate");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");
em.setJpaPropertyMap(properties);

return em;
}

@Bean
public PlatformTransactionManager primaryTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(primaryEntityManager().getObject());
return transactionManager;
}

}

3 SecondaryConfig.java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "secondaryEntityManager",
transactionManagerRef = "secondaryTransactionManager", basePackages = {"com.download.integration.repositories.secondary"})
public class SecondaryConfig {

@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter adaptor = new HibernateJpaVendorAdapter();
adaptor.setShowSql(false);
adaptor.setGenerateDdl(false);
adaptor.setDatabase(Database.MYSQL);
return adaptor;
}

@Bean(name = "secondaryDataSource")
public DataSource secondaryDataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://127.0.0.1:3306/secondarydb");
ds.setUsername("user");
ds.setPassword("password");
return ds;
}

@Bean(name = "secondaryEntityManager")
public LocalContainerEntityManagerFactoryBean secondaryEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(secondaryDataSource());
em.setPackagesToScan(new String[] {"com.download.domain.secondary"});

HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("hibernate.hbm2ddl.auto", "validate");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");
em.setJpaPropertyMap(properties);

return em;
}

@Bean
public PlatformTransactionManager secondaryTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(secondaryEntityManager().getObject());
return transactionManager;
}

}

希望这有帮助。

关于java - Spring Data Autowiring 多个数据源失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31754014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com