Java Spring Boot:需要一个无法找到的名为“entityManagerFactory”的 bean

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46391867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:20:26  来源:igfitidea点击:

Spring Boot : required a bean named 'entityManagerFactory' that could not be found

javaspringspring-boot

提问by Tien Nguyen

Error:

错误:

Description:

Field userRepository in nashtech.tiennguyenm3.config.DataSeedingListener required a bean of type 'nashtech.tiennguyenm3.dao.IUserRepository' that could not be found.

Action:

Consider defining a bean of type 'nashtech.tiennguyenm3.dao.IUserRepository' in your configuration.

描述:

nashtech.tiennguyenm3.config.DataSeedingListener 中的字段 userRepository 需要一个无法找到的“nashtech.tiennguyenm3.dao.IUserRepository”类型的 bean。

行动:

考虑在您的配置中定义一个类型为“nashtech.tiennguyenm3.dao.IUserRepository”的 bean。

Code:

代码:

package nashtech.tiennguyenm3.musicstore;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages={"nashtech.tiennguyenm3"})
public class MusicStoreApplication {

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

DataSeedingListener.java

数据种子监听器.java

package nashtech.tiennguyenm3.config;

import java.util.HashSet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import nashtech.tiennguyenm3.dao.IRoleRepository;
import nashtech.tiennguyenm3.dao.IUserRepository;
import nashtech.tiennguyenm3.model.Role;
import nashtech.tiennguyenm3.model.User;

@Component
public class DataSeedingListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private IUserRepository userRepository;

    @Autowired
    private IRoleRepository roleRepository;

    @Autowired 
    private PasswordEncoder passwordEncoder;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent arg0) {
        // Roles
        if (roleRepository.findByName("ROLE_ADMIN") == null) {
            roleRepository.save(new Role("ROLE_ADMIN"));
        }

        if (roleRepository.findByName("ROLE_MEMBER") == null) {
            roleRepository.save(new Role("ROLE_MEMBER"));
        }

        // Admin account
        if (userRepository.findByEmail("[email protected]") == null) {
            User admin = new User();
            admin.setEmail("[email protected]");
            admin.setPassword(passwordEncoder.encode("123456"));
            HashSet<Role> roles = new HashSet<>();
            roles.add(roleRepository.findByName("ROLE_ADMIN"));
            roles.add(roleRepository.findByName("ROLE_MEMBER"));
            admin.setRoles(roles);
            userRepository.save(admin);
        }

        // Member account
        if (userRepository.findByEmail("[email protected]") == null) {
            User user = new User();
            user.setEmail("[email protected]");
            user.setPassword(passwordEncoder.encode("123456"));
            HashSet<Role> roles = new HashSet<>();
            roles.add(roleRepository.findByName("ROLE_MEMBER"));
            user.setRoles(roles);
            userRepository.save(user);
        }
    }
}

IUserReponsitory.java

IUserReponsiory.java

package nashtech.tiennguyenm3.dao;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import nashtech.tiennguyenm3.model.User;

@Repository
public interface IUserRepository extends CrudRepository<User, Integer> {
    public User findByEmail(String email);
}

application.properties

应用程序属性

# ===============================
# DATASOURCE
# ===============================

# Set here configurations for the database connection

# Connection url for the database "mycontact"
spring.datasource.url=jdbc:mysql://localhost:8181/db_musicstore

# MySQL username and password 
spring.datasource.username=root
spring.datasource.password=

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.dbcp.test-while-idle=true
spring.datasource.dbcp.validation-query=SELECT 1

# ===============================
# JPA / HIBERNATE
# ===============================

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).

# Show or not log for each sql query
spring.jpa.show-sql=true

# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto=update

# Naming strategy
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.ImprovedNamingStrategy

# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

security.basic.enabled=false

When I add (scanBasePackages={"nashtech.tiennguyenm3"}) after @SpringBootApplication, this error occurs.

当我在@SpringBootApplication 之后添加 (scanBasePackages={"nashtech.tiennguyenm3"}) 时,会发生此错误。

回答by msp

You need to annotate your application class with @EnableJpaRepositoriesin order to have the @Repositorybean created.

您需要注释您的应用程序类,@EnableJpaRepositories以便@Repository创建 bean。

@SpringBootApplication(scanBasePackages={"nashtech.tiennguyenm3"})
@EnableJpaRepositories(basePackageClasses = IUserRepository.class) // <-- add this
public class MusicStoreApplication {

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

回答by Alex P.

If all your repositories/daos are under the package nashtech.tiennguyenm3.daothen you can add:

如果您的所有存储库/daos 都在包下,nashtech.tiennguyenm3.dao那么您可以添加:

@SpringBootApplication(scanBasePackages={"nashtech.tiennguyenm3"})
@EnableJpaRepositories(basePackages = "nashtech.tiennguyenm3.dao")
public class MusicStoreApplication {

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

If they are in different packages then you can add this:

如果它们在不同的包中,那么您可以添加以下内容:

@SpringBootApplication(scanBasePackages={"nashtech.tiennguyenm3"})
@EnableJpaRepositories(basePackages = { "nashtech.tiennguyenm3.dao", "the.other.package"})
public class MusicStoreApplication {

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