Java NoSuchBeanDefinitionException:未定义名为“entityManagerFactory”的 bean

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28544412/
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-11 06:23:10  来源:igfitidea点击:

NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined

javaspring-mvcspring-data-jpa

提问by Son

I have simple Spring 4 WebMVC app (Java-config), and I want to add JPA. But when I try to run app (as deloyed on Tomcat) I get: What can be a source of error?

我有简单的 Spring 4 WebMVC 应用程序(Java-config),我想添加 JPA。但是当我尝试运行应用程序(如在 Tomcat 上部署)时,我得到:什么可能是错误的来源?

Error creating bean with name 'indexController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.demo.webtemplate.db.repository.CustSysRepository org.demo.webtemplate.controllers.IndexController.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'custSysRepository': Cannot create inner bean '(inner bean)#f4da8a0' 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)#f4da8a0': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined

创建名为“indexController”的 bean 时出错:注入自动装配的依赖项失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配字段:org.demo.webtemplate.db.repository.CustSysRepository org.demo.webtemplate.controllers.IndexController.repository; 嵌套异常是 org.springframework.beans.factory.BeanCreationException:创建名为 'custSysRepository' 的 bean 时出错:在设置 bean 时无法创建 [org.springframework.orm.jpa.SharedEntityManagerCreator] 类型的内部 bean '(inner bean)#f4da8a0'财产'实体经理';嵌套异常是 org.springframework.beans.factory.BeanCreationException:创建名为 '(inner bean)#f4da8a0' 的 bean 时出错:无法解析对 bean 'entityManagerFactory' 的引用 在设置构造函数参数时;嵌套异常是 org.springframework.beans.factory。NoSuchBeanDefinitionException:未定义名为“entityManagerFactory”的 bean

Initializer:

初始化程序:

package org.demo.webtemplate;

...

public class SpringWebMvcInitializer implements WebApplicationInitializer  {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(Config.class);
        ctx.setServletContext(servletContext);
        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
    }

}

Config:

配置:

package org.demo.webtemplate;

...

@Configuration
@EnableWebMvc
@ComponentScan("pl.bzwbk.webtemplate")
@EnableJpaRepositories("pl.bzwbk.webtemplate.db.repository")
public class Config {

    @Bean
    public UrlBasedViewResolver setupViewResolver() {
        UrlBasedViewResolver resolver = new UrlBasedViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }
}

Controller:

控制器:

package org.demo.webtemplate.controllers;

...

@Controller
public class IndexController {

    @Autowired
    CustSysRepository repository;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        List<CustSys> clients = repository.findByFullName("SOME NAME");

        return "index"+clients .size();
    }

}

Repository:

存储库:

package org.demo.webtemplate.db.repository;

...

public interface CustSysRepository extends JpaRepository<CustSys, Long> {

    List<CustSys> findByFullName(String fullName);
}

Entity:

实体:

package org.demo.webtemplate.db.entity;

...

@Entity
@Table(name = "CUST_SYS")
public class CustSys implements Serializable {
    private static final long serialVersionUID = 1L;
    ...
    @Size(max = 255)
    @Column(name = "FULL_NAME")
    private String fullName;
    ...
    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }
    ...
}

application.properties:

应用程序属性:

jdbc.driverClassName=org.hsqldb.jdbc.JDBCDriver
jdbc.url=jdbc:hsqldb:mem:testdb
jdbc.user=sa
jdbc.pass=

回答by rikica

You're missing completly DB configuration in your Configclass.

您在Config课堂上完全缺少数据库配置。

Try this for example:

试试这个,例如:

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("org.hsqldb.jdbc.JDBCDriver");
    dataSource.setUrl("jdbc:hsqldb:mem:testdb");
    dataSource.setUsername("sa");
    dataSource.setPassword("");
    return dataSource;
}

@Bean
public EntityManager entityManager() {
    return entityManagerFactory().getObject().createEntityManager();
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource());
    em.setPackagesToScan("package.where.your.entites.like.CustSys.are.stored");
    return em;
}

回答by Heri

in this questionI posted a full example how to unit test a spring controller which needs an autowired JpaRepository.

这个问题中,我发布了一个完整的示例,如何对需要自动装配的 JpaRepository 的弹簧控制器进行单元测试。