복붙노트

[SPRING] NoSuchBeanDefinitionException SessionFactory 빈을 초기화하는 방법?

SPRING

NoSuchBeanDefinitionException SessionFactory 빈을 초기화하는 방법?

나는 질문이있다. Spring과 Hibernate를 사용하여 웹 응용 프로그램을 실행하려했는데 이상한 오류가 있습니다. NoSuchBeanDefinitionException. 스택 트레이스 :

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:967)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:837)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:749)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)

이유는 모르겠다. 왜냐하면 내 servlet-context.xml에서 SessionFacory bean을 선언했기 때문이다.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.2.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

<context:component-scan base-package="com.example" />
<context:component-scan base-package="com.example.service" />
<context:component-scan base-package="com.example.service.impl" />
<context:component-scan base-package="com.example.dao" />
<context:component-scan base-package="com.example.dao.impl.hibernate" />
<context:component-scan base-package="com.example.web.controller" />
<context:component-scan base-package="com.example.entity" />

<mvc:annotation-driven />

<tx:annotation-driven />

<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

<bean
    class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/pages/" />
    <property name="suffix" value=".jsp" />
</bean>

<bean id="userService" class="com.example.service.impl.UserServiceImpl">
    <property name="userDAO" ref="userDAO" />
</bean>

<bean id="userDAO" class="com.example.dao.impl.hibernate.HibernateUserDAO" />

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="driverClassName" value="org.h2.Driver" />
    <property name="url" value="jdbc:h2:~/userdb" />
    <property name="username" value="user" />
    <property name="password" value="pswd" />
</bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="annotatedClasses">
        <list>
            <value>com.example.entity.User</value>
            <value>com.example.entity.Role</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <value>
            hibernate.dialect=org.hibernate.dialect.H2Dialect
            hibernate.show_sql=true
        </value>
    </property>
</bean>

<bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

또한 모든 DAO 구현과 서비스 구현에 주석을 달았습니다. 어떤 아이디어?

추가됨

이것은 내 코드의 일부입니다.

@Repository
public class HibernateUserDAO implements UserDAO {
   @Autowired
   private SessionFactory sessionFactory;
   ...
}

서비스 클래스 :

@Service
public class UserServiceImpl implements UserService, UserDetailsService {
@Autowired
private UserDAO userDAO;

@Override
@Transactional
public void create(User user) throws SQLException {
    userDAO.create(user);
}

전체 스택 추적 :

Sep 20, 2013 10:54:10 AM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class   
org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name         'hibernateUserDAO': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.example.dao.impl.hibernate.HibernateUserDAO.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=sessionFactory)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1120)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
 Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire               field: private org.hibernate.SessionFactory    com.example.dao.impl.hibernate.HibernateUserDAO.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=sessionFactory)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 23 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=sessionFactory)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:967)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:837)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:749)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
... 25 more

이것은 내 web.xml입니다.

<?xml version="1.0" encoding="UTF-8"?>

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/root-context.xml
        /WEB-INF/application-security.xml
    </param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>hibernateFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>hibernateFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

해결법

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

    1.구성을 정리하는 것으로 시작하겠습니다.

    구성을 정리하는 것으로 시작하겠습니다.

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

    이 모든 것을 포함합니다.

    <context:component-scan base-package="com.example" />
    <context:component-scan base-package="com.example.service" />
    <context:component-scan base-package="com.example.service.impl" />
    <context:component-scan base-package="com.example.dao" />
    <context:component-scan base-package="com.example.dao.impl.hibernate" />
    <context:component-scan base-package="com.example.web.controller" />
    <context:component-scan base-package="com.example.entity" />
    

    구성 요소 검색을 사용하고 있으므로 모든 Bean을 명시 적으로 정의 할 필요가 없습니다 (여전히 필요한 경우 구성 요소 검색을 거의 쓸모 없게 만듭니다).

    다음에이 두 콩

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
    
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
    

    이미

    기본적으로 당신에게 이것을 남긴다.

    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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.2.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
    
    <context:component-scan base-package="com.example" />
    
    <mvc:annotation-driven />
    <tx:annotation-driven />
    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="org.h2.Driver" />
        <property name="url" value="jdbc:h2:~/userdb" />
        <property name="username" value="user" />
        <property name="password" value="pswd" />
    </bean>
    
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.example.entity.User</value>
                <value>com.example.entity.Role</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.H2Dialect
                hibernate.show_sql=true
            </value>
      </property>
    </bean>
    
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    

    구성이 불완전하지만 구성이 잘못된 위치에 있기 때문에 오류가 발생하지 않기 때문에 문제가 해결되지는 않습니다. 데이터 소스, sessionFactory, transactionManager 및 은 applicationContext.xml로 이동해야합니다. Nex에는 applicationContext.xml에도 컨트롤러를 제외한 모든 항목을 검색하는 구성 요소 검색이 포함되어야합니다.

        <context:component-scan base-package="com.example">
        <context:exclude-filter type="annotation" value="org.springframework.stereotype.Controller" />
    </context:component-scan">
    

    servlet-context.xml의 을 다음과 같이 변경하십시오.

    <context:component-scan base-package="com.example" use-default-filters="false">
        <context:include-filter type="annotation" value="org.springframework.stereotype.Controller" />
    </context:component-scan">
    

    @Service 및 @Repository 빈의 중복 인스턴스화를 방지하기 위해. ContextLoaderListener와 DispatcherServlet이 같은 bean을 로딩하고 생성하고 있습니다. 좋은 예외와 다른 메모리로의 각 bean의 인스턴스가 2 개씩 있습니다.

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

    2.때때로 Spring이 실제로 말하고자하는 것은 :

    때때로 Spring이 실제로 말하고자하는 것은 :

    There are multiple bean definitions...
    

    나는이 문제가 있었다 :

    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'metadataGeneratorFilter' is defined
    

    한 번 내가 어디서 이런 XML 파일을 가지고 :

    <security:custom-filter ref="metadataGeneratorFilter" before="CHANNEL_FILTER"/>
    
    <beans:bean id="metadataGeneratorFilter"
                class="org.springframework.security.saml.metadata.  MetadataGeneratorFilter">
        <beans:constructor-arg ref="metadataGenerator"/>
    </beans:bean>
    
  3. ==============================

    3.@Autowired를 사용하면 컨텍스트에서 속성처럼 선언 할 필요가 없습니다. 그러나 컨텍스트에 있어야합니다. ---> NoSuchBeanDefinition -> 찾지 못했습니다.

    @Autowired를 사용하면 컨텍스트에서 속성처럼 선언 할 필요가 없습니다. 그러나 컨텍스트에 있어야합니다. ---> NoSuchBeanDefinition -> 찾지 못했습니다.

    <bean id="userService" class="com.example.service.impl.UserServiceImpl">
        <property name="userDAO" ref="userDAO" /> 
    </bean>
    

    속성 컨텍스트에서 userDAO를 제거하십시오. 자동 라우트하면 컨텍스트에서 필요하지 않습니다.

    그러나 문제는이 콩에있는 것처럼 보인다.

    <bean id="userDAO" class="com.example.dao.impl.hibernate.HibernateUserDAO" />
    

    sessionFactory의 종속성을 주입 할 수는 없지만 모든 것이 올바른 것처럼 보입니다. 세션 팩토리에서 @autowired를 제거하려고하지 마십시오. hibernateUserDao의 컨텍스트에서 add 속성 참조를 가져 오거나 설정하십시오.

  4. from https://stackoverflow.com/questions/18911356/nosuchbeandefinitionexception-how-to-initialise-sessionfactory-bean by cc-by-sa and MIT license