错误 - NoSuchBeanDefinitionException:没有名为“entityManagerFactory”的bean可用

Posted

技术标签:

【中文标题】错误 - NoSuchBeanDefinitionException:没有名为“entityManagerFactory”的bean可用【英文标题】:Error - NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available 【发布时间】:2020-10-23 06:03:05 【问题描述】:

我正在尝试使用 spring-batch 和 jpa 开发一个新批次。当我尝试启动它时,我收到错误“嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available”

这里是我的 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.test.batch</groupId>
    <artifactId>test-be-batch</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>test-be-batch</name>
    <description>Modulo applicativo batch per reportistica</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-boot-admin.version>2.2.3</spring-boot-admin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-batch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-entitymanager</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-test</artifactId>
            <scope>test</scope>
        </dependency>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>de.codecentric</groupId>
                <artifactId>spring-boot-admin-dependencies</artifactId>
                <version>$spring-boot-admin.version</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

我的数据源配置类:

package com.test.testid.batch.testidbebatch.configuration;

import javax.sql.DataSource;

import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
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;

@Configuration
@EntityScan(basePackages = "com.test.testid.batch.testidbebatch.dao.eid.entity")
@EnableJpaRepositories(basePackages = "com.test.testid.batch.testidbebatch.dao.eid.repository")
public class DatasourceEidConfiguration 
    
    @Bean
    @Primary
    @ConfigurationProperties("persistence.datasource.xid")
    public DataSourceProperties testIdDataSourceProperties() 
        return new DataSourceProperties();
    

    @Bean
    @Primary
    @ConfigurationProperties("persistence.datasource.xid.hikari")
    public DataSource testIdDataSource() 
        return testIdDataSourceProperties().initializeDataSourceBuilder().build();
    



我的存储库类:

package com.test.testid.batch.testidbebatch.dao.eid.repository;

import java.util.Date;
import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.test.testid.batch.testidbebatch.dao.eid.entity.UserReportsLog;

@Repository
public interface UserReportsLogRepository extends JpaRepository<UserReportsLog, Integer> 

    @Query("SELECT usl.legalEntity, usl.serviceProvider, usl.eventType, count(1) as number "
            + "FROM UserReportsLogs usl where usl.createdOn = :extractionDate")
    public List<Object[]> getReports(@Param("extractionDate") Date extractionDate);


我的实体类:

package com.test.testid.batch.testidbebatch.dao.eid.entity;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user_reports_log")
@Cacheable
public class UserReportsLog implements Serializable 

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "event_type")
    private String eventType;

    @Column(name = "legal_entity")
    private String legalEntity;

    @Column(name = "service_provider")
    private String serviceProvider;

    @Column(name = "test_id")
    private String testid;

    @Column(name = "email")
    private String email;

    @Column(name = "mobile")
    private String mobile;

    @Column(name = "old_username")
    private String oldUsername;
    

    @Column(name = "created_on")
    private Date createdOn;

    public Integer getId() 
        return id;
    

    public void setId(Integer id) 
        this.id = id;
    

    public String getEventType() 
        return eventType;
    

    public void setEventType(String eventType) 
        this.eventType = eventType;
    

    public String getLegalEntity() 
        return legalEntity;
    

    public void setLegalEntity(String legalEntity) 
        this.legalEntity = legalEntity;
    

    public String getServiceProvider() 
        return serviceProvider;
    

    public void setServiceProvider(String serviceProvider) 
        this.serviceProvider = serviceProvider;
    

    public String gettestid() 
        return testid;
    

    public void settestid(String testid) 
        this.testid = testid;
    

    public String getEmail() 
        return email;
    

    public void setEmail(String email) 
        this.email = email;
    

    public String getMobile() 
        return mobile;
    

    public void setMobile(String mobile) 
        this.mobile = mobile;
    

    public String getOldUsername() 
        return oldUsername;
    

    public void setOldUsername(String oldUsername) 
        this.oldUsername = oldUsername;
    

    public Date getCreatedOn() 
        return createdOn;
    

    public void setCreatedOn(Date createdOn) 
        this.createdOn = createdOn;
    


Application.properties:

persistence.datasource.xid.type=com.zaxxer.hikari.HikariDataSource
persistence.datasource.xid.url=$jdbc:postgresql://xxxx:1234/xxx?currentSchema=xid
persistence.datasource.xid.driverClassName=org.postgresql.Driver
persistence.datasource.xid.username=$DB_USERNAME:xxx
persistence.datasource.xid.password=$DB_PASSWORD:xxx
persistence.datasource.xid.platform=postgresql
persistence.datasource.xid.hikari.minimumIdle=$DB_testID_DS_MIN_IDLE:2
persistence.datasource.xid.hikari.maximumPoolSize=$DB_testID_DS_MAX_POOL_SIZE:10
persistence.datasource.xid.hikari.idleTimeout=$DB_testID_DS_IDLE_TIMEOUT:30000
persistence.datasource.xid.hikari.poolName=$DB_testID_DS_POOL_NAME:MBEHikariCP
persistence.datasource.xid.hikari.maxLifetime=$DB_testID_DS_MAX_LIFETIME:2000000
persistence.datasource.xid.hikari.connectionTimeout=$DB_testID_DS_CONNECTION_TIMEOUT:30000

如果我尝试启动应用程序,我会收到错误:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.4.RELEASE)

2020-07-02 16:30:46.750  INFO 5168 --- [           main] c.e.e.b.e.testidBeBatchApplication       : Starting testidBeBatchApplication on vt-name with PID 5168 (C:\dev\testid-batch\target\classes started by name in C:\dev\testid-batch)
2020-07-02 16:30:46.754 DEBUG 5168 --- [           main] c.e.e.b.e.testidBeBatchApplication       : Running with Spring Boot v2.2.4.RELEASE, Spring v5.2.3.RELEASE
2020-07-02 16:30:46.754  INFO 5168 --- [           main] c.e.e.b.e.testidBeBatchApplication       : No active profile set, falling back to default profiles: default
2020-07-02 16:30:47.534  INFO 5168 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-07-02 16:30:47.768  INFO 5168 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 224ms. Found 1 JPA repository interfaces.
2020-07-02 16:30:49.094  INFO 5168 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-07-02 16:30:49.118  INFO 5168 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'com.test.testid.connector.data.configuration.SpringDataConfigurationDefault' of type [com.test.testid.connector.data.configuration.SpringDataConfigurationDefault] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-07-02 16:30:49.123  INFO 5168 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'performanceMonitorAdvisor' of type [org.springframework.aop.support.DefaultPointcutAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-07-02 16:30:49.551  INFO 5168 --- [           main] io.undertow.servlet                      : Initializing Spring embedded WebApplicationContext
2020-07-02 16:30:49.552  INFO 5168 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2751 ms
2020-07-02 16:30:49.958  WARN 5168 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userReportsLogRepository': Cannot create inner bean '(inner bean)#51d719bc' 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)#51d719bc': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
2020-07-02 16:30:49.977  INFO 5168 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-07-02 16:30:50.106 ERROR 5168 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

A component required a bean named 'entityManagerFactory' that could not be found.


Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

有人可以帮助我吗?

【问题讨论】:

您使用的是哪个 Hibernate ORM 版本?可能与 Spring Boot 版本不匹配。 好点,我改变 pom 删除排除形式 spring-boot-starter-data-jpa 并删除依赖 org.eclipse.persistence org.eclipse.persistence.jpa。现在连接到数据源的工作....我有一个 java.lang.IllegalArgumentException: Validation failed for query for public abstract java.util.List com.test.testid.batch.testidbebatch.dao.xid.repository.UserReportsLogRepository .getReports(java.util.Date)!但我认为这是另一个问题 请编辑您的问题,使其对其他人更具可读性,尤其是样板实体方法。为什么要从启动器依赖项中排除休眠? 【参考方案1】:

您正在调用方法testIdDataSourceProperties,而不是bean。

试试这个:

@Bean
@Primary
@ConfigurationProperties("persistence.datasource.xid.hikari")
public DataSource testIdDataSource(@Autowired DataSourceProperties dataSourceProperties) 
    return dataSourceProperties.initializeDataSourceBuilder().build();

【讨论】:

你好,我已经按照你说的试过了。我收到同样的错误

以上是关于错误 - NoSuchBeanDefinitionException:没有名为“entityManagerFactory”的bean可用的主要内容,如果未能解决你的问题,请参考以下文章

远程服务器返回错误: 404错误远程服务器返回错误:500错误 HttpWebResponse远程服务器返回错误:(404500) 错误。

Pig 安装错误:错误 pig.Main:错误 2998:未处理的内部错误

Informix 错误:发生了语法错误。错误代码:-201

我收到一个错误:“MetaMask - RPC 错误:错误:错误:[ethjs-rpc] rpc 错误与有效负载”

错误精灵错误跟踪器错误

网页打开显示错误500是啥意思