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

[Spring Boot]控制器需要一个名为“entityManagerFactory”的名称,但找不到该名称

袁宜
2023-03-14

我正在尝试部署我的spring应用程序。以下是pom的副本。xml文件。

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>gs-spring-boot</artifactId>
    <version>0.0.1</version>
    <url>http://maven.apache.org</url>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties> 

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
    </parent> 

    <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.postgresql</groupId>
                <artifactId>postgresql</artifactId>
                <version>42.2.2</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-test</artifactId>
                <scope>test</scope>
            </dependency>       
            <!-- https://mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2 -->
            <dependency>
                <groupId>org.springframework.security.oauth</groupId>
                <artifactId>spring-security-oauth2</artifactId>
                <version>2.3.3.RELEASE</version>
            </dependency>

            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version> 5.2.1.Final</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-entitymanager</artifactId>
                <version>5.2.3.Final</version>
            </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <packaging>pom</packaging>
</project>

以下是申请的副本。属性文件。

spring.datasource.jdbc-url=jdbc:postgresql://ec2-54-204-18-53.compute-1.amazonaws.com:5432/d695rcqcr9r06e?user=poevxwkkkdcuho&password=d519b6781db3cdf4c615df7c24deaa2ef741f47458cb98c66e5d1b6f68c3e3c8&ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory
spring.driverClassName=org.postgresql.Driver
spring.datasource.username=xxxx
spring.datasource.password=xxxx    
spring.datasource.type=com.zaxxer.hikari.HikariDataSource



spring.jpa.properties.dialect=org.hibernate.dialect.PostgreSQL94Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL94Dialect
#hibernate.dialect: org.hibernate.dialect.PostgreSQL95Dialect

logging.level.org.org.springframework.retry=DEBUG
management.security.enabled=false

我得到的错误跟踪如下。

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

2018-10-28 14:27:56.545  INFO 16678 --- [           main] com.loanguruhub.RestController           : Starting RestController on TheKing with PID 16678 (/media/dhiral/Media/java/gs-loanguru-hub/target/classes started by dhiral in /media/dhiral/Media/java/gs-loanguru-hub)
2018-10-28 14:27:56.554  INFO 16678 --- [           main] com.loanguruhub.RestController           : No active profile set, falling back to default profiles: default
2018-10-28 14:27:56.810  INFO 16678 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@28c4711c: startup date [Sun Oct 28 14:27:56 IST 2018]; root of context hierarchy
2018-10-28 14:27:58.871  INFO 16678 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'clientDetailsService' with a different definition: replacing [Root bean: class [org.springframework.aop.scope.ScopedProxyFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in BeanDefinition defined in class path resource [org/springframework/security/oauth2/config/annotation/configuration/ClientDetailsServiceConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=authorizationServerConfig; factoryMethodName=clientDetailsService; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/loanguruhub/security/AuthorizationServerConfig.class]]
2018-10-28 14:28:00.785  INFO 16678 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-10-28 14:28:02.022  INFO 16678 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-10-28 14:28:02.070  INFO 16678 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-10-28 14:28:02.070  INFO 16678 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.31
2018-10-28 14:28:02.099  INFO 16678 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib]
2018-10-28 14:28:02.286  INFO 16678 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-10-28 14:28:02.287  INFO 16678 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 5490 ms
2018-10-28 14:28:02.854  INFO 16678 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-10-28 14:28:02.855  INFO 16678 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-10-28 14:28:02.855  INFO 16678 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-10-28 14:28:02.855  INFO 16678 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-10-28 14:28:02.856  INFO 16678 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-10-28 14:28:02.856  INFO 16678 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'corsFilter' to: [/*]
2018-10-28 14:28:02.856  INFO 16678 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-10-28 14:28:03.017  WARN 16678 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'companyController': Unsatisfied dependency expressed through field 'companyResouces'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'companyResources': Cannot create inner bean '(inner bean)#75504cef' 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)#75504cef': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
2018-10-28 14:28:03.024  INFO 16678 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2018-10-28 14:28:03.072  INFO 16678 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-10-28 14:28:03.219 ERROR 16678 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

Field companyResouces in com.loanguruhub.controller.CompanyController required a bean named 'entityManagerFactory' that could not be found.


Action:

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

我被夹在中间。我几乎没试过什么东西。因为提供entityManager的hibernate JPA启动器是从pom中删除hibernate核心和hibernate实体管理器的。xml也是如此。但我也犯了同样的错误。除此之外,我还创建了自定义datasoruce,如下所示。

@Configuration
public class DatabaseConfiguration {
    @Bean
    @ConfigurationProperties("spring.datasource")
    public DataSourceProperties dataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @ConfigurationProperties("spring.datasource")
    public HikariDataSource dataSource(DataSourceProperties properties) {
        return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
                .build();
    }
}

并试图做同样的事情。但又犯了同样的错误。任何帮助都是值得的。

=======更新========公司控制器代码。

@RestController
@RequestMapping(
        path = "/company",
        produces=MediaType.APPLICATION_JSON_VALUE,
        consumes=MediaType.APPLICATION_JSON_VALUE)
public class CompanyController {
    @Autowired
    private CompanyResources companyResouces;
}

与JDBC-URL相关的错误跟踪

Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.IllegalArgumentException: dataSource or dataSourceClassName or jdbcUrl is required.
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:732) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]

共有1个答案

宰父跃
2023-03-14

有两件事需要解决,然后就可以工作了。。

>

  • 因为你使用的是Spring data jpa,所以hibernate是默认实现,所以不需要显式定义hibernate依赖项,因为这可能会产生冲突,所以从pom中删除这个:

       <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version> 5.2.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.2.3.Final</version>
        </dependency>
    

    因为你也在传递数据源用户名和密码,所以从url中删除传递参数:所以从它中删除用户名和密码spring.datasource.url,只有用户名和密码从spring.datasource.username

    从Spring Boot2. xhikari是默认连接池,Spring data jpa将根据应用程序自动配置数据源。

    @Configuration
    public class DatabaseConfiguration
    

  •  类似资料: