没有可用的名为“ entityManagerFactory”的bean

时间:2019-11-07 20:21:14

标签: hibernate spring-boot jpa

我创建了一个Spring Boot应用程序,并使用要执行的方法创建了一个类。当将项目部署为war文件时,我从stacktrace中得到了错误。我想从TennisExecutor类运行该方法。

  • 没有名为'entityManagerFactory'的bean
  • 创建名称为'(inner bean)#366583f9'的bean时出错:设置构造函数参数时无法解析对bean'entityManagerFactory'的引用;嵌套的异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有名为'entityManagerFactory'的bean

我将显示代码的某些部分:


@Configuration
@EnableAsync
@EnableScheduling
@ComponentScan(basePackages={"parser", "service", "processing", "automation"})
public class TennisExecutor extends SpringBootServletInitializer {

    @Autowired
    @Qualifier("tennisDataSource")
    private DataSource dataSource;

    @Autowired
    @Qualifier("tennisTm")
    PlatformTransactionManager transactionManager;

    @Autowired
    public ParseUpcomingMatchesFile parseUpcomingMatchesFile;

    @Autowired
    public ParseFinishedMatchesFile parseFinishedMatchesFile;

    @Autowired
    public PlayersProcessor playersProcessor;

    public TennisExecutor() {}

    @Scheduled(cron = "0 */2 * * * ?")
    public void executeTasks() throws IOException {

         parseUpcomingMatchesFile.parseMatchesFile(webDriver, new File(ConstantData.TOMORROW_UPCOMING_MATCHES_FILE_PATH));

     }

@Configuration
@EnableJpaRepositories(basePackageClasses = {ParseUpcomingMatchesFile.class, ParseFinishedMatchesFile.class,
        PlayersProcessor.class}, entityManagerFactoryRef = "tennisEmf", transactionManagerRef = "tennisTm")
@EnableTransactionManagement
class ApplicationConfig {

    @Bean
    public EntityManagerFactoryBuilder builder(Environment environment) {
        Map<String, String> jpaProperties = new HashMap<>();
        jpaProperties.put("hibernate.show_sql", environment.getProperty("spring.jpa.show-sql"));
        jpaProperties.put("hibernate.format_sql", environment.getProperty("spring.jpa.properties.hibernate.format_sql"));
        jpaProperties.put("hibernate.dialect", environment.getProperty("spring.jpa.properties.hibernate.dialect"));
        return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), jpaProperties, null);
    }

    @Bean(name = "tennisDataSource")
    public DataSource dataSource(Environment environment) {

        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(environment.getRequiredProperty("spring.datasource.url"));
        dataSource.setUsername(environment.getRequiredProperty("spring.datasource.username"));
        dataSource.setPassword(environment.getRequiredProperty("spring.datasource.password"));
        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean tennisEmf(@Qualifier("tennisDataSource") DataSource tennisDataSource, EntityManagerFactoryBuilder builder) {
        return builder.dataSource(tennisDataSource).packages(ParseUpcomingMatchesFile.class, ParseFinishedMatchesFile.class, PlayersProcessor.class).persistenceUnit("tennisPersistenceUnit").build();
    }

    @Bean
    public JpaTransactionManager tennisTm(@Qualifier("tennisEmf") EntityManagerFactory emf) {
        return new JpaTransactionManager(emf);
    }
}
@Component
@Transactional(value = "tennisTm")
@EnableJpaRepositories(basePackageClasses={MatchesRepository.class, PlayersRepository.class}, entityManagerFactoryRef = "tennisEmf")
public class ParseUpcomingMatchesFile {

    @PersistenceContext(unitName = "tennisPersistenceUnit")
    EntityManager entityManager;

    @Autowired
    public MatchesRepository matchesRepository;

    @Autowired
    public PlayersRepository playersRepository;

    static final org.apache.log4j.Logger logger = Logger.getLogger(ParseUpcomingMatchesFile.class);

    public ParseUpcomingMatchesFile() {
    }

    public void parseMatchesFile(WebDriver webDriver, File file) throws IOException {

    String fullNameOne = "player1";
    String fullNameTwo = "player2";
    int matchId = matchesRepository.selectIdByPlayerNames(fullNameOne, fullNameTwo);

    }
}
@Configuration
public class DatasourceConfig {

    @Autowired
    @Qualifier("tennisDataSource")
    private DataSource dataSource;

    @Autowired
    @Qualifier("tennisTm")
    PlatformTransactionManager transactionManager;

    public EntityManagerFactory setDataSource() {

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setPersistenceUnitName("tennisPersistenceUnit");
        factoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        factoryBean.afterPropertiesSet();

        EntityManagerFactory factory = factoryBean.getNativeEntityManagerFactory();
        return factory;
    }
}

@Repository
public interface MatchesRepository extends CrudRepository<MatchesEntity, Integer> {   

    @Query(value = "select m from MatchesEntity m")
    List<MatchesEntity> selectAllMatches();

    @Query(value = "select m.id from MatchesEntity m where m.namePlayer1 = :namePlayer1 and " +
            "m.namePlayer2 = :namePlayer2")
    int selectIdByPlayerNames(String namePlayer1, String namePlayer2);

   }

Stacktrace:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'tennisExecutor': Unsatisfied dependency expressed through field 'parseUpcomingMatchesFile'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parseUpcomingMatchesFile': Unsatisfied dependency expressed through field 'matchesRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'matchesRepository': Cannot create inner bean '(inner bean)#366583f9' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#366583f9': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:742)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:389)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:311)
    at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:151)
    at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:131)
    at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:91)
    at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:171)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5225)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 44 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parseUpcomingMatchesFile': Unsatisfied dependency expressed through field 'matchesRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'matchesRepository': Cannot create inner bean '(inner bean)#366583f9' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#366583f9': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1251)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
    ... 66 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'matchesRepository': Cannot create inner bean '(inner bean)#366583f9' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#366583f9': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:361)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:131)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1681)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1433)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1251)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
    ... 79 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#366583f9': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:314)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:110)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:662)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:479)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:346)
    ... 92 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:771)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1221)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:303)

我试图删除.m2 / repository文件夹,添加了spring-data-jpa的依赖项,但没有任何变化。另外,我尝试配置数据源以实现某些目的,但是它不起作用。 有人有什么建议吗?

2 个答案:

答案 0 :(得分:0)

对于Spring Boot 2,您需要添加此依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

答案 1 :(得分:0)

Sampada 解决方案有效。干得好:)