簡體   English   中英

Spring-boot:需要一個無法找到的名為“entityManagerFactory”的 bean

[英]Spring-boot: required a bean named 'entityManagerFactory' that could not be found

我正在使用 JPA 開發 Spring Boot 應用程序並遇到此錯誤。 我不確定我是否使用了正確的注釋或缺少依賴項。 任何幫助將不勝感激。

這是錯誤信息

1:05:28 AM: Executing external task 'bootRun'...
:compileJava
:processResources UP-TO-DATE
:classes
:findMainClass
:bootRun
01:05:35.198 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
01:05:35.201 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
01:05:35.201 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/C:/Users/zahid/IdeaProjects/giflib/build/classes/main/, file:/C:/Users/zahid/IdeaProjects/giflib/build/resources/main/]

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

2018-01-24 01:05:35.539  INFO 14840 --- [  restartedMain] com.sweng.giflib.Application             : Starting Application on DESKTOP-EKFI3C8 with PID 14840 (C:\Users\zahid\IdeaProjects\giflib\build\classes\main started by zahid in C:\Users\zahid\IdeaProjects\giflib)
2018-01-24 01:05:35.540  INFO 14840 --- [  restartedMain] com.sweng.giflib.Application             : No active profile set, falling back to default profiles: default
2018-01-24 01:05:35.828  INFO 14840 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@396ad740: startup date [Wed Jan 24 01:05:35 CST 2018]; root of context hierarchy
2018-01-24 01:05:37.685  INFO 14840 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-01-24 01:05:37.697  INFO 14840 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service Tomcat
2018-01-24 01:05:37.699  INFO 14840 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.14
2018-01-24 01:05:37.800  INFO 14840 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-01-24 01:05:37.801  INFO 14840 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1976 ms
2018-01-24 01:05:37.991  INFO 14840 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-01-24 01:05:37.992  INFO 14840 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-01-24 01:05:37.992  INFO 14840 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-01-24 01:05:37.992  INFO 14840 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-01-24 01:05:37.993  INFO 14840 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-01-24 01:05:37.994  INFO 14840 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2018-01-24 01:05:38.291  WARN 14840 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfig': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userServiceImpl': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Cannot create inner bean '(inner bean)#64397422' 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)#64397422': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
2018-01-24 01:05:38.294  INFO 14840 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2018-01-24 01:05:38.321  INFO 14840 --- [  restartedMain] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-01-24 01:05:38.444 ERROR 14840 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

Field userRepository in com.sweng.giflib.service.UserServiceImpl required a bean named 'entityManagerFactory' that could not be found.


Action:

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


BUILD SUCCESSFUL

Total time: 9.681 secs
1:05:38 AM: External task execution finished 'bootRun'.

構建.gradle

buildscript {
    ext {
        springBootVersion = '1.5.3.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}


group 'com.sweng'
version '1.0-SNAPSHOT'


apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'

repositories {
    mavenCentral()
}

springBoot {
    mainClass = "com.sweng.giflib.Application"
}
dependencies {
    compile "org.springframework.boot:spring-boot-starter-data-jpa:$springBootVersion"
    compile "org.springframework.boot:spring-boot-starter-web:$springBootVersion"
    compile "org.springframework.boot:spring-boot-starter-thymeleaf:$springBootVersion"
    compile "org.springframework.boot:spring-boot-devtools:$springBootVersion"
    compile "mysql:mysql-connector-java"
    compile "org.springframework.boot:spring-boot-starter-security:$springBootVersion"
    compile "org.thymeleaf.extras:thymeleaf-extras-springsecurity4:2.1.2.RELEASE"

    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
}

應用程序屬性

spring.datasource.url== jdbc:mysql://localhost:3306/giflib
spring.db.driver= com.mysql.jdbc.Driver
spring.datasource.username = su
spring.datasource.password = 
spring.jpa.show-sql = true
#spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming.strategy = org.hibernate.cfg.ImprovedNamingStrategy

應用程序.java

package com.sweng.giflib;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@ComponentScan
@Configuration
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
@EnableJpaRepositories(basePackages = "com.sweng.giflib.repository")
@SpringBootApplication(scanBasePackages= "com.sweng.giflib")

public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

}

用戶服務.java

package com.sweng.giflib.service;

import com.sweng.giflib.model.User;
import org.springframework.security.core.userdetails.UserDetailsService;

public interface UserService extends UserDetailsService {
    User findByUsername(String username);
}

UserServiceImpl.java

package com.sweng.giflib.service;

import com.sweng.giflib.repository.UserRepository;
import com.sweng.giflib.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public User findByUsername(String username)
    {
        return userRepository.findByusername(username);
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // Load user from the database (throw exception if not found)
        User user = userRepository.findByusername(username);
        if(user == null) {
            throw new UsernameNotFoundException("User not found");
        }

        // Return user object
        return user;
    }

}

用戶存儲庫.java

package com.sweng.giflib.repository;


import com.sweng.giflib.model.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends CrudRepository<User, Long>{
    User findByusername(String name);

}

用戶.java

package com.sweng.giflib.model;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Entity
public class User implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    @Size(min = 8, max = 20)
    private String username;

    @Column(length = 100)
    private String password;

    @Column(nullable = false)
    private boolean enabled;

    @OneToOne
    @JoinColumn(name = "role_id")
    private Role role;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(role.getName()));
        return authorities;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}

我收到錯誤消息,例如“需要一個無法找到的名為‘entityManagerFactory’的 bean”。

經過大量的谷歌搜索解決了這個問題。 我為 JPA 設置了手動配置。

@Bean 
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); 

    return sessionFactory;
}

但 JPA 默認按名稱搜索 sessionFactory ' entityManagerFactory '所以將我的代碼更改為:

@Bean(name="entityManagerFactory")
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

    return sessionFactory;
} 

對我來說,我忘記從排除項中刪除DataSourceAutoConfiguration.class

所以這個:

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
// Main class definition

應該是:

@SpringBootApplication()
// Main class definition

嘗試將 spring boot 連接到 mysql 數據庫時遇到同樣的問題。

拯救我的是將正確版本的 hibernate-core 添加到我的 pom 文件中。 從休眠 5.2.0 開始。 不再需要 hibernate-entitymanager。 Hibernate-core 5.2.0 在處理收集時存在 Spring Data JPA 問題。 如果您使用的是 Spring Data JPA, Hibernate-core 5.2.1及更高版本適用於 Spring Data JPA。

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

在我們的例子中工作正常,但不適用於@WebMvcTest 的測試

花了一段時間才發現,但問題是:

@SpringBootApplication
@ComponentScan({"com.givenproject"})
@EntityScan("com.givenproject")
@EnableJpaRepositories("com.givenproject")
@Configuration
public class Application {

而是做:

@SpringBootApplication
@Configuration
public class Application {

@Configuration
@ComponentScan({"com.givenproject"})
@EntityScan(basePackages = "com.givenproject")
@EnableJpaRepositories(basePackages = "com.givenproject")
public class DataConfig {
}

我遇到了這個問題,因為我在測試硬編碼值時忘記刪除添加的注釋@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class }) 只需使用@SpringBootApplication即可解決該問題

您要么需要刪除exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class} (在這種情況下 Spring 將自動配置您的數據源)或手動配置您的數據源

@Bean
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
    return new YourCustomDataSource();
}

更新:似乎您的屬性中有一些錯誤:

spring.datasource.url== jdbc:mysql://localhost:3306/giflib
spring.db.driver= com.mysql.jdbc.Driver

嘗試從第一行中刪除額外的=並為第二行使用spring.datasource.driver-class-name屬性名稱:

spring.datasource.url=jdbc:mysql://localhost:3306/giflib
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

還要向您的 MySQL 依賴項添加一個版本:

compile "mysql:mysql-connector-java:6.0.6"

我認為由於這些錯誤,Spring 無法正確自動檢測您的數據源類型。

您已選擇繞過 EntityManagerFactory 的自動創建。 因此,您應該在其中一個配置類中添加以下兩個 bean,可能在 Application 類中。

private static String PROP_DB_DRIVER_CLASS = "spring.db.driver";
private static String PROP_DB_URL = "spring.datasource.url";
private static String PROP_DB_USER = "spring.datasource.username";
private static String PROP_DB_PASS = "spring.datasource.password";

@Autowired
private Environment env;

@Bean
public DataSource dataSource(){
      DriverManagerDataSource dataSource = new DriverManagerDataSource();
      dataSource.setDriverClassName(env.getProperty(PROP_DB_DRIVER_CLASS));
      dataSource.setUrl(env.getProperty(PROP_DB_URL));
      dataSource.setUsername(env.getProperty(PROP_DB_USER));
      dataSource.setPassword(env.getProperty(PROP_DB_PASS));
      return dataSource;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
      LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
      em.setDataSource(dataSource());
      em.setPackagesToScan("com.sweng.giflib.model");

      JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
      em.setJpaVendorAdapter(vendorAdapter);
      em.setJpaProperties(additionalProperties());

      return em;
}

不要忘記將 hibernate 依賴項添加到您的項目中。

在我的例子中,問題是在@SpringBootApplication注釋中聲明的exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class} ,所以感謝 Kirill Simonov 的提示,我解決了花了一整天的時間搜索和解決問題的問題。 經過幾個小時的嘗試,刪除它對我來說非常好。 其他一切都很好,@Service、@Autowired、@EnableAutoConfiguration 和 @ComponentScan 在這個 Spring Boot 版本中是多余的,所以真的有很多時間在互聯網上嘗試技巧。

我正在使用 spring boot 2.1.11.RELEASE 版本。

編程是一件很有趣的事情,一旦我使用排除解決方案來解決錯誤消息,那么現在的問題就是同樣的事情。 所以沒有魔法咒語或公式,因為這個宇宙有很多不同的場景,即使它與我們之前研究過的場景相似。

就我而言,我刪除了 mysql 連接器的版本並讓 spring boot 處理它。 它奏效了。

除了提到的建議之外,我還嘗試了多種方法來消除此錯誤。只需從 application.properties 中刪除以下代碼,我就解決了此錯誤

spring.jpa.properties.hibernate.cache.use_second_level_cache=true                                                   
spring.jpa.properties.hibernate.cache.use_query_cache=false                                                         
spring.jpa.properties.hibernate.generate_statistics=false                                                           
spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM