[Spring-Boot] Контроллер требует, чтобы был назван entityManagerFactory, который не может быть найден - PullRequest
0 голосов
/ 28 октября 2018

Я пытаюсь развернуть мое весеннее приложение.Ниже приведена копия файла 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>

Ниже приведена копия файла application.properties.

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.

Я застрял между ними.Я пробовал несколько вещей.Начиная с версии hibernate-JPA, предоставляющей entityManager, также передаются hibernate-core и hibernate-entity-manager из pom.xml.Но ту же ошибку я получил.В дополнение к этому я создал пользовательские данные, как показано ниже.

@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();
    }
}

и попытался сделать то же самое.но получил ту же ошибку снова.любая помощь приветствуется.

====== Обновление ======= Код CompanyController.

@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 Ответ

0 голосов
/ 28 октября 2018

Есть пара вещей, которые необходимо исправить, затем они должны работать ..

  1. Поскольку вы используете данные весны 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>
    
  2. Поскольку вы также передаете имя пользователя и пароль для источника данных, удалите передаваемый параметр из URL: удалите из него имя пользователя и пароль spring.datasource.url и имеют только имя пользователя и пароль от spring.datasource.username & spring.datasource.password.

  3. из весенней загрузки 2.x hikari - пул соединений по умолчанию, и Spring data jpa автоматически настроит вашисточник данных на основе приложения .properties, поэтому также удалите конфигурацию: удалите класс ниже:

    @Configuration
    public class DatabaseConfiguration
    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...