복붙노트

[SPRING] Spring JPA (Hibernate) 유형의 정규 bean이 없다 : javax.persistence.EntityManagerFactory

SPRING

Spring JPA (Hibernate) 유형의 정규 bean이 없다 : javax.persistence.EntityManagerFactory

저는 Spring-boot를 사용하고 있습니다. 그래서 Tomcat 7에서 전개 된 전쟁입니다. 앱을 시작하면 다음과 같은 결과를 얻습니다 :

  Dec 30, 2013 7:41:06 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcherServlet'
2013-12-30 19:41:06 INFO  DispatcherServlet:461 - FrameworkServlet 'dispatcherServlet': initialization started
  2013-12-30 19:41:06 INFO  SimpleUrlHandlerMapping:315 - Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
  2013-12-30 19:41:06 INFO  RequestMappingHandlerMapping:181 - Mapped "{[/user],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public com.cloudfordev.controlpanel.orm.User com.cloudfordev.controlpanel.GetController.getUser(int)
  2013-12-30 19:41:07 INFO  SimpleUrlHandlerMapping:315 - Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
  2013-12-30 19:41:07 INFO  SimpleUrlHandlerMapping:315 - Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
  2013-12-30 19:41:08 INFO  DispatcherServlet:480 - FrameworkServlet 'dispatcherServlet': initialization completed in 1957 ms
  Dec 30, 2013 7:41:08 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Dec 30, 2013 7:41:08 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Dec 30, 2013 7:41:08 PM org.apache.coyote.AbstractProtocol stop
INFO: Stopping ProtocolHandler ["http-nio-8080"]
Dec 30, 2013 7:41:08 PM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["http-nio-8080"]
Dec 30, 2013 7:41:08 PM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service Tomcat
Dec 30, 2013 7:41:08 PM org.apache.coyote.AbstractProtocol stop
INFO: Stopping ProtocolHandler ["http-nio-8080"]
Dec 30, 2013 7:41:08 PM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["http-nio-8080"]
2013-12-30 19:41:08 INFO  AutoConfigurationReportLoggingInitializer$AutoConfigurationReportLogger:108 -


=========================
AUTO-CONFIGURATION REPORT
=========================


Positive matches:
-----------------

   MessageSourceAutoConfiguration
      - @ConditionalOnMissingBean (types: org.springframework.context.MessageSource; SearchStrategy: all) found no beans (OnBeanCondition)

   PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer
      - @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) found no beans (OnBeanCondition)

   DataSourceAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType (OnClassCondition)
      - @ConditionalOnClass classes found: org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType (OnClassCondition)

   DataSourceTransactionManagerAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.jdbc.core.JdbcTemplate,org.springframework.transaction.PlatformTransactionManager (OnClassCondition)
      - @ConditionalOnClass classes found: org.springframework.jdbc.core.JdbcTemplate,org.springframework.transaction.PlatformTransactionManager (OnClassCondition)

   JpaBaseConfiguration.JpaWebConfiguration
      - found web application StandardServletEnvironment (OnWebApplicationCondition)
      - SpEL expression on org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration$JpaWebConfiguration: #{true} (OnExpressionCondition)

   DispatcherServletAutoConfiguration
      - found web application StandardServletEnvironment (OnWebApplicationCondition)
      - @ConditionalOnClass classes found: org.springframework.web.servlet.DispatcherServlet (OnClassCondition)
      - found web application StandardServletEnvironment (OnWebApplicationCondition)
      - @ConditionalOnClass classes found: org.springframework.web.servlet.DispatcherServlet (OnClassCondition)
      - @ConditionalOnBean (types: org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; SearchStrategy: all) found the following [tomcatEmbeddedServletContainerFactory] (OnBeanCondition)

   DispatcherServletAutoConfiguration#dispatcherServlet
      - no DispatcherServlet found (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition)

   EmbeddedServletContainerAutoConfiguration
      - found web application StandardServletEnvironment (OnWebApplicationCondition)
      - found web application StandardServletEnvironment (OnWebApplicationCondition)

   EmbeddedServletContainerAutoConfiguration.EmbeddedTomcat
      - @ConditionalOnClass classes found: javax.servlet.Servlet,org.apache.catalina.startup.Tomcat (OnClassCondition)
      - @ConditionalOnClass classes found: javax.servlet.Servlet,org.apache.catalina.startup.Tomcat (OnClassCondition)
      - @ConditionalOnMissingBean (types: org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; SearchStrategy: current) found no beans (OnBeanCondition)

   ServerPropertiesAutoConfiguration#serverProperties
      - @ConditionalOnMissingBean (types: org.springframework.boot.context.embedded.properties.ServerProperties; SearchStrategy: all) found no beans (OnBeanCondition)

   WebMvcAutoConfiguration
      - found web application StandardServletEnvironment (OnWebApplicationCondition)
      - @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.servlet.DispatcherServlet,org.springframework.web.servlet.config.annota
tion.WebMvcConfigurerAdapter (OnClassCondition)
      - found web application StandardServletEnvironment (OnWebApplicationCondition)
      - @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.servlet.DispatcherServlet,org.springframework.web.servlet.config.annota
tion.WebMvcConfigurerAdapter (OnClassCondition)
      - @ConditionalOnMissingBean (types: org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; SearchStrategy: all) found no beans (OnBeanCondition)

   WebMvcAutoConfiguration#hiddenHttpMethodFilter
      - @ConditionalOnMissingBean (types: org.springframework.web.filter.HiddenHttpMethodFilter; SearchStrategy: all) found no beans (OnBeanCondition)

   WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#defaultViewResolver
      - @ConditionalOnMissingBean (types: org.springframework.web.servlet.view.InternalResourceViewResolver; SearchStrategy: all) found no beans (OnBeanCondition)


Negative matches:
-----------------

   RabbitAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.amqp.rabbit.core.RabbitTemplate,com.rabbitmq.client.Channel (OnClassCondition)

   AopAutoConfiguration
      - required @ConditionalOnClass classes not found: org.aspectj.lang.annotation.Aspect,org.aspectj.lang.reflect.Advice (OnClassCondition)

   BatchAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.batch.core.launch.JobLauncher (OnClassCondition)

   JpaRepositoriesAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.data.jpa.repository.JpaRepository (OnClassCondition)

   MongoRepositoriesAutoConfiguration
      - required @ConditionalOnClass classes not found: com.mongodb.Mongo,org.springframework.data.mongodb.repository.MongoRepository (OnClassCondition)

   DataSourceAutoConfiguration.DbcpConfiguration
      - org.apache.commons.dbcp.BasicDataSource DataSource class not found (DataSourceAutoConfiguration.BasicDatabaseCondition)

   DataSourceAutoConfiguration.EmbeddedConfiguration
      - no embedded database detected (DataSourceAutoConfiguration.EmbeddedDatabaseCondition)

   DataSourceAutoConfiguration.JdbcTemplateConfiguration
      - no existing bean configured database (DataSourceAutoConfiguration.DatabaseCondition)

   DataSourceAutoConfiguration.TomcatConfiguration
      - org.apache.tomcat.jdbc.pool.DataSource DataSource class not found (DataSourceAutoConfiguration.TomcatDatabaseCondition)

   DataSourceTransactionManagerAutoConfiguration#transactionManager
      - @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) found no beans (OnBeanCondition)

   JmsTemplateAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.jms.core.JmsTemplate,javax.jms.ConnectionFactory (OnClassCondition)

   DeviceResolverAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.mobile.device.DeviceResolverHandlerInterceptor,org.springframework.mobile.device.DeviceHandlerMethodArgumentResolver (OnClassCondition)

   HibernateJpaAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean,org.springframework.transaction.annotation.EnableTransactionManagement,javax.persistence.EntityManager,org.hibernate.ejb.HibernateEntityManager (OnClassCondition)
      - @ConditionalOnClass classes found: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean,org.springframework.transaction.annotation.EnableTransactionManagement,javax.persistence.EntityManager,org.hibernate.ejb.HibernateEntityManager (OnClassCondition)
      - @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) found no beans (OnBeanCondition)

   ReactorAutoConfiguration
      - required @ConditionalOnClass classes not found: reactor.spring.context.config.EnableReactor (OnClassCondition)

   ThymeleafAutoConfiguration
      - required @ConditionalOnClass classes not found: org.thymeleaf.spring3.SpringTemplateEngine (OnClassCondition)

   EmbeddedServletContainerAutoConfiguration.EmbeddedJetty
      - required @ConditionalOnClass classes not found: org.eclipse.jetty.server.Server,org.eclipse.jetty.util.Loader (OnClassCondition)

   MultipartAutoConfiguration
      - @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.multipart.support.StandardServletMultipartResolver (OnClassCondition)
      - @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.multipart.support.StandardServletMultipartResolver (OnClassCondition)
      - @ConditionalOnBean (types: javax.servlet.MultipartConfigElement; SearchStrategy: all) found no beans (OnBeanCondition)

   WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#beanNameViewResolver
      - @ConditionalOnBean (types: org.springframework.web.servlet.View; SearchStrategy: all) found no beans (OnBeanCondition)

   WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#viewResolver
      - @ConditionalOnBean (types: org.springframework.web.servlet.View; SearchStrategy: all) found no beans (OnBeanCondition)

   WebSocketAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.web.socket.WebSocketHandler (OnClassCondition)



  java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
        at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:356)

        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1180)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:300)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:660)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:552)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:293)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:749)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:738)
        at com.cloudfordev.controlpanel.Application.main(Application.java:14)
        ... 6 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined
        at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:559)
        at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:515)
        at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:682)
        at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:655)
        at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:150)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
        at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:353)

        ... 22 more

내 응용 프로그램 부팅 방법은 다음과 같습니다.

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {

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

Spring 컨트롤러가 연결을 처리 할 때 :

@Controller
public class GetController {

    private UserService userService;

    @Autowired 
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public @ResponseBody User getUser(@RequestParam(value="id", required=true) int id) {
        User user = null;

        user = userService.getUser(id);

        return user;
    }
}

userService에서 getUser를 수행합니다.

@Component
public class UserService {

    private UserDAO UserDao;

    public UserDAO getUserDao() {
        return UserDao;
    }

    @Autowired
    public void setUserDao(UserDAO UserDao) {
        this.UserDao = UserDao;
    }

    public User getUser(int id) {
        return getUserDao().load(id);
    }
}

엔티티를 찾기 위해 userDao를 사용하는 :

@Repository("userDao")
@Transactional(propagation=Propagation.REQUIRED)
public class UserDAO {

    @PersistenceContext
    private EntityManager entityManager;

    public void insert(User user) {
        entityManager.persist(user);
    }

    public User load(int id) {
        return entityManager.find(User.class, id);
    }
}

나는 / src / main / resources에 다음과 같은 spring-config.xml을 가지고있다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd
           http://www.springframework.org/schema/tx  
           http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.mydomain.orm" />

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceXmlLocation" value="classpath:/persistence.xml" />
        <property name="persistenceUnitName" value="userPersistenceUnit" />
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
        <property name="jpaDialect" ref="jpaDialect" />
    </bean>

    <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="database" value="HSQL" />
        <property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
    </bean>

    <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
        <property name="dataSource" ref="dataSource" />
        <property name="jpaDialect" ref="jpaDialect" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5432/mydb" />
        <property name="username" value="my_user" />
        <property name="password" value="" />
    </bean>
</beans>

마지막으로 다음과 같은 /src/main/resources/persistence.xml이 있습니다.

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    version="1.0">
    <persistence-unit name="userPersistenceUnit" transaction-type="RESOURCE_LOCAL" >
    <class>com.mydomain.orm.User</class>
</persistence-unit>
</persistence>  

이 오류를 해결하려면 무엇을해야합니까?

해결법

  1. ==============================

    1.EntityManager가 주입되기를 원하지만 필드에 주입 주석이 없으며 어떤 경우에도 "factory"는 잘못된 한정자입니다. 필요한 경우 unitName을 사용하여 @PersistenceContext로 필드에 주석을 붙여 여러 지속성 단위를 구별합니다.

    EntityManager가 주입되기를 원하지만 필드에 주입 주석이 없으며 어떤 경우에도 "factory"는 잘못된 한정자입니다. 필요한 경우 unitName을 사용하여 @PersistenceContext로 필드에 주석을 붙여 여러 지속성 단위를 구별합니다.

    편집 된 질문에 대한 답변 : Application 클래스에서 시작했기 때문에 XML 파일이 포함되지 않으며, Spring은 @ComponentScan 바로 다음에옵니다. 이 가져 오기를 Application 클래스 (또는 스캔 된 @Configuration 클래스)에 추가합니다.

    @ImportResource("classpath:spring-config.xml")
    

    또는 XML 구성을 JavaConfig 형식으로 마이그레이션 할 수 있습니다.이 형식은 Spring에서 구성 요소 검색을 수행합니다.

  2. ==============================

    2.귀하의 문제는 귀하가 이미 Annotation Bean에 대한 클래스 경로를 검색하는 주석 구성을 사용하고 있다는 것입니다.이 Bean은 UserDAO를 인스턴스화하려고 시도하지만 여기에 EntityManagerFactory를 제공하지 않습니다.

    귀하의 문제는 귀하가 이미 Annotation Bean에 대한 클래스 경로를 검색하는 주석 구성을 사용하고 있다는 것입니다.이 Bean은 UserDAO를 인스턴스화하려고 시도하지만 여기에 EntityManagerFactory를 제공하지 않습니다.

    @ImportResource ( "classpath : spring-config.xml")를 통해 JavaConfig와 XML 구성을 결합 할 수 있습니다.

    
    @Configuration
    @ComponentScan
    @EnableAutoConfiguration
    @ImportResource("classpath:spring-config.xml")
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    
    
    @Controller
    public class GetController {
        @Autowired
        UserService userService;
    
        @RequestMapping(value = "/user", method = RequestMethod.GET)
        public @ResponseBody User getUser(@RequestParam(value="id", required=true) int id) {
    
            return userService.getUser(id);
        }
    }
    
    
    
    @Component
    public class UserService {
    
        @Autowired
        private UserDAO UserDao;
    
        public User getUser(int id) {
            return getUserDao().load(id);
        }
    }
    

    다량의 상용구 코드를 저장하는 DAO를 위해 SpringData를 사용할 것을 제안 할 수 있습니다.

  3. ==============================

    3.충돌에서 나온 자동 구성 보고서를 보면 정의 된 DataSource가 없음을 알 수 있습니다. classpath에 html이나 hsqldb가 포함되어 있다면, classpath에 맞는 것들이 있다면 Spring Boot가 만들어 줄 것입니다.

    충돌에서 나온 자동 구성 보고서를 보면 정의 된 DataSource가 없음을 알 수 있습니다. classpath에 html이나 hsqldb가 포함되어 있다면, classpath에 맞는 것들이 있다면 Spring Boot가 만들어 줄 것입니다.

    덧붙여 말하자면, Spring Boot를 올바른 방법으로 사용한다면 XML 파일은 중복됩니다.

  4. from https://stackoverflow.com/questions/20808290/spring-jpa-hibernate-no-qualifying-bean-of-type-javax-persistence-entitymanag by cc-by-sa and MIT license