简体   繁体   English

Spring Boot EntityManagerFactoryBuilder 未自动装配

[英]Spring Boot EntityManagerFactoryBuilder not autowired

In a Spring Boot application I'm trying to setup multiple database connections.在 Spring Boot 应用程序中,我试图设置多个数据库连接。 I've started building the primary datasource, but I'm getting the following error on the mySqlEntityManagerFactory method.我已经开始构建主数据源,但在 mySqlEntityManagerFactory 方法上出现以下错误。

Could not autowire.无法自动装配。 no beans of EntityManagerFactoryBuilder没有 EntityManagerFactoryBuilder 的 bean

import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.PersistenceContext;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@Transactional
@EnableTransactionManagement
@EnableJpaRepositories(
        basePackages = "digital.sheppard.dao",
        entityManagerFactoryRef = "entityManager",
        transactionManagerRef = "transactionManager")
public class PrimaryDBConfig {

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

    @PersistenceContext(unitName = "primary")
    @Primary
    @Bean(name = "entityManager")
    public LocalContainerEntityManagerFactoryBean mySqlEntityManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(mysqlDataSource()).persistenceUnit("primary").properties(jpaProperties())
                .packages("digital.sheppard.model").build();
    }

    private Map<String, Object> jpaProperties() {
        Map<String, Object> props = new HashMap<String, Object>();
        props.put("hibernte.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");
        props.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");

        return props;
    }

}

How would I autowire the EntityManagerFactoryBuilder?我将如何自动装配 EntityManagerFactoryBuilder?

I'm trying to follow the code on this blog https://raymondhlee.wordpress.com/2015/10/31/configuring-multiple-jpa-entity-managers-in-spring-boot/我正在尝试遵循此博客上的代码https://raymondhlee.wordpress.com/2015/10/31/configuring-multiple-jpa-entity-managers-in-spring-boot/

Here's the main application class if it's helpful如果有帮助,这是主要的应用程序类

@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@ComponentScan
public class Application extends SpringBootServletInitializer {

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

}

我认为您应该删除此代码

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

将参数名称builder更改为entityManagerFactoryBuilder以注入 JpaBaseConfiguration.class 中的 bean

Have you tried to remove your exclusion of 'DataSourceAutoConfiguration' ?您是否尝试删除对 'DataSourceAutoConfiguration' 的排除?

Using '@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})' prevent a lot of beans from beeing created.使用 '@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})' 可以防止创建大量 bean。

If you got a problem when using a datasource and adding this is your solution, maybe it's not the right one.如果您在使用数据源时遇到问题并添加这是您的解决方案,则可能它不是正确的。

Know that spring boot detect the presence of certain classes in the classpath.知道 spring boot 会检测类路径中某些类的存在。 If you're using maven, it's reading all classes from all dependencies.如果您使用的是 maven,它会从所有依赖项中读取所有类。

So consider let this DataSourceAutoConfiguration.class running;所以考虑让这个 DataSourceAutoConfiguration.class 运行;

cheers干杯

It could be, notice that just could be, your main class is not at the top of the "class tree".可能是,注意可能是,您的主类不在“类树”的顶部。 Spring needs to scan all classes that are a child (according to package convention) starting from the main class. Spring 需要从主类开始扫描所有子类(根据包约定)。

Maybe you would read https://www.baeldung.com/spring-component-scanning也许您会阅读https://www.baeldung.com/spring-component-scanning

If your classes aren't been read by spring scan, they will never be into spring context.如果您的类没有被 spring 扫描读取,它们将永远不会进入 spring 上下文。

Couple of possibilities : You need to add the @EnableJpaRepositories(basePackages = {"your.pkg.here"}) to the Application .几种可能性:您需要将 @EnableJpaRepositories(basePackages = {"your.pkg.here"}) 添加到 Application 。 This tells Spring Data to look for your repository classes under the specified package.这告诉 Spring Data 在指定的包下查找您的存储库类。

The exception is due to public LocalContainerEntityManagerFactoryBean mySqlEntityManagerFactory(EntityManagerFactoryBuilder builder) { which expects a bean of EntityManagerFactoryBuilder .异常是由于public LocalContainerEntityManagerFactoryBean mySqlEntityManagerFactory(EntityManagerFactoryBuilder builder) {需要一个 bean 的EntityManagerFactoryBuilder

I checked the reference link, I am not sure if that code will work.我检查了参考链接,我不确定该代码是否有效。

Typically, one creates an instance of LocalContainerEntityManagerFactoryBean and initializes it as per need.通常,创建 LocalContainerEntityManagerFactoryBean 的实例并根据需要对其进行初始化。 In your case you can do在你的情况下,你可以做

  LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
  em.setDataSource(mysqlDataSource());
  em.setPersistenceUnitName("primary");
  em.setPackagesToScan(new String[] { "digital.sheppard.model" });

  JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
  em.setJpaVendorAdapter(vendorAdapter);
  em.setJpaProperties(jpaProperties());

The persistence unit name should be same as defined in persistence.xml , though the file is now optional when using Spring JPA.持久性单元名称应与persistence.xml定义的相同,尽管在使用Spring JPA 时该文件现在是可选的。

For a non spring version check out https://stackoverflow.com/a/26814642/776548对于非弹簧版本,请查看https://stackoverflow.com/a/26814642/776548

Also

  • since you are initializing EntityManagerFactory by yourself, we will have to exclude DataSourceAutoConfiguration.class .由于您自己初始化 EntityManagerFactory,我们不得不排除DataSourceAutoConfiguration.class
  • @Primary is only required if you want multiple datasources.仅当您需要多个数据源时才需要@Primary If you have only one, consider removing the annotation, and add it when you need to have multiple data sources如果只有一个,可以考虑去掉注解,需要有多个数据源的时候再添加

对我来说,删除错误添加的多个数据源上的@Primary 解决了这个问题

it was caused by your ide software,set up these options这是由你的ide软件引起的,设置这些选项在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM