当前位置: 首页 > 知识库问答 >
问题:

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

齐飞星
2023-03-14

我正在尝试开发一个新的批与Spring批和jpa。当我尝试启动它时,我收到错误"嵌套异常是org.springframework.beans.factory.NoSuchBean定义异常:没有名为'entityManagerFactory'可用的bean"

我的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;
    }

}

pplication.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.

有人能帮我吗?

共有1个答案

唐元青
2023-03-14

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

试试这个:

@Bean
@Primary
@ConfigurationProperties("persistence.datasource.xid.hikari")
public DataSource testIdDataSource(@Autowired DataSourceProperties dataSourceProperties) {
    return dataSourceProperties.initializeDataSourceBuilder().build();
}
 类似资料:
  • 我创建了一个Spring Boot应用程序,并使用我想要执行的方法创建了一个类。将项目部署为war文件时,我从stacktrac中获取错误。我想从类TennisExecitor中运行该方法。 没有名为'entityManagerFactory'的bean可用 创建名为'(内部bean)#366583f9'的bean时出错:设置构造函数参数时无法解析对bean'entityManagerFactor

  • 我在构建时遇到了这个错误。我在这里参考了其他的答案,但没有一个对我有效。 应用程序.属性 存储库: 实体: 和pom.xml 和主类(spring boot应用程序) 我从.m2目录中删除了所有文件夹。再次运行mvn clean install。得到了同样的错误。服务类自动连接存储库。控制器使用@RestController注释。 而这正是确切的原因: 原因:org.springframework

  • 我正在开发一个新的应用程序(对我来说),我在启动时收到了无bean“entityManagerFactory”可用错误。其他经历过这种情况的人表示,如果我正确定义了数据源,这种情况就不会发生。让我困惑的是,Spring Boot/JPA或Flyway(我也在使用)坚持将特定的属性名称用于您的一个数据源。我不知道如果你有一个以上的人会怎么处理。我需要更改我们的申请。属性文件,以便从环境变量中获取值,

  • 我正在SpringBoot中构建一个“Hello World”的基本程序 代码 MyController.java DemoApplication.java

  • 我有一个Spring启动应用程序。我用@Component注释了项目的一个类。现在在我的主类中,当我试图获取该类的bean时,我得到一个异常,它无法找到该bean。 注释为组件的类如下

  • 我想开发一个模块化的应用程序,使用MySql数据库,Java11和Spring启动。在我添加模块描述符之前,这个应用程序运行得非常好;所以我只能猜测我在module-info.java中丢失了一些东西,但我不知道它是什么。我感谢任何帮助。这是我的密码 波姆。xml 应用yml module-info.java 使用者JAVA UsersRepository.java 用户资源。JAVA 演示应用程