创建 Spring bean 时出错

Posted

技术标签:

【中文标题】创建 Spring bean 时出错【英文标题】:Error creating Spring bean 【发布时间】:2013-10-06 07:44:10 【问题描述】:

我正在使用 Spring 3.1.4

控制器类

package com.demo.scheduler.controller;

import java.util.Map;

import com.demo.scheduler.service.SchedulerService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class SchedulerController 

    private SchedulerService service;

    @Autowired
    public SchedulerController(SchedulerService service) 
        this.service = service;

    

    @RequestMapping(value = "/tasklist",method = RequestMethod.GET)
    public String listTask(Map<String, Object> model) 
        model.put("task", service.getTask());

        return "tasklist";

    

服务实现

package com.demo.scheduler.service;

import com.demo.scheduler.TaskConfig;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class SchedulerServiceImpl implements SchedulerService 
    @Autowired
    public SchedulerDAO schedulerDAO;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public List<TaskConfig> getTask() 

        return schedulerDAO.getTask();
    


DAO 实现

package com.demo.scheduler.dao;

import com.demo.scheduler.TaskConfig;

import java.util.List;

import org.hibernate.SessionFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class HibernateDAO implements SchedulerDAO 

    @Autowired
    private SessionFactory sessionFactory;

    public HibernateDAO(SessionFactory sessionFactory) 
        this.sessionFactory = sessionFactory;

    

    @SuppressWarnings("unchecked")
    @Override
    public List<TaskConfig> getTask() 

        return sessionFactory.getCurrentSession().createCriteria(
                TaskConfig.class).list();
    


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>demoscheduler</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>demo</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class></servlet>

    <servlet-mapping>
        <servlet-name>demo</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping><session-config>
        <session-timeout>60</session-timeout>
    </session-config>
</web-app>

demo-servlet.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: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/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-3.0.xsd">

    <context:component-scan base-package="com.demo.scheduler" />
    <context:annotation-config />
    <tx:annotation-driven />

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

    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>/WEB-INF/resources/hibernate.properties
            </value>
        </property>
    </bean>


    <bean class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
        id="sessionFactory">
        <property name="dataSource" ref="dataSource">
        </property>
        <property name="configLocations">
            <list>
                <value>/WEB-INF/resources/schedulerTask.hbm.xml
                </value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">$hibernate.dialect</prop>
                <prop key="hibernate.show_sql">$hibernate.show_sql</prop>
                <prop key="hibernate.format_sql">$hibernate.format_sql</prop>
                <prop key="hibernate.connection.provider_class">$hibernate.connection.provider_class
                </prop>
                <prop key="hibernate.c3p0.acquire_increment">$hibernate.c3p0.acquire_increment
                </prop>
                <prop key="hibernate.c3p0.idle_test_period">$hibernate.c3p0.idle_test_period
                </prop>
                <prop key="hibernate.c3p0.max_size">$hibernate.c3p0.max_size
                </prop>
                <prop key="hibernate.c3p0.max_statements">$hibernate.c3p0.max_statements
                </prop>
                <prop key="hibernate.c3p0.min_size">$hibernate.c3p0.min_size
                </prop>
                <prop key="hibernate.c3p0.timeout">$hibernate.c3p0.timeout
                </prop>
            </props>
        </property>
    </bean>

    <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        id="dataSource">

        <property name="driverClassName" value="$hibernate.connection.driver_class" />
        <property name="url" value="$hibernate.connection.url" />
        <property name="username" value="$hibernate.connection.username" />
        <property name="password" value="$hibernate.connection.password" />
    </bean>



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

</beans>

更新代码后,我收到以下错误:

9544 [http-4186-2] 错误 org.springframework.web.servlet.DispatcherServlet - 上下文 初始化失败 org.springframework.beans.factory.BeanCreationException:错误 创建名为“schedulerController”的bean:注入自动装配 依赖失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:不能 自动装配字段:私有 com.demo.scheduler.service.SchedulerService com.demo.scheduler.controller.SchedulerController.service;嵌套的 例外是 org.springframework.beans.factory.BeanCreationException: 创建名为“schedulerServiceImpl”的 bean 时出错:注入 自动装配依赖失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:不能 自动装配字段:public com.demo.scheduler.dao.SchedulerDAO com.demo.scheduler.service.SchedulerServiceImpl.schedulerDAO;嵌套的 例外是 org.springframework.beans.factory.BeanCreationException: 创建名为“hibernateDAO”的 bean 时出错:注入自动装配 依赖失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:不能 自动装配字段:私有 org.hibernate.SessionFactory com.demo.scheduler.dao.HibernateDAO.sessionFactory;嵌套异常 是 org.springframework.beans.factory.BeanCreationException: 错误 创建 ServletContext 中定义的名称为“sessionFactory”的 bean 资源[/WEB-INF/applicationContext.xml]:init方法的调用 失败的;嵌套异常是 java.lang.NullPointerException at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) 在 org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) 在 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) 在 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) 在 org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607) 在 org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925) 在 org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472) 在 org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631) 在 org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588) 在 org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645) 在 org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508) 在 org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449) 在 org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133) 在 javax.servlet.GenericServlet.init(GenericServlet.java:212) 在 org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1161) 在 org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:806) 在 org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129) 在 org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) 在 org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) 在 org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) 在 org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) 在 org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263) 在 org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) 在 org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584) 在 org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) 在 java.lang.Thread.run(Thread.java:662) 引起: org.springframework.beans.factory.BeanCreationException:不能 自动装配字段:私有 com.demo.scheduler.service.SchedulerService com.demo.scheduler.controller.SchedulerController.service;嵌套的 例外是 org.springframework.beans.factory.BeanCreationException: 创建名为“schedulerServiceImpl”的 bean 时出错:注入 自动装配依赖失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:不能 自动装配字段:public com.demo.scheduler.dao.SchedulerDAO com.demo.scheduler.service.SchedulerServiceImpl.schedulerDAO;嵌套的 例外是 org.springframework.beans.factory.BeanCreationException: 创建名为“hibernateDAO”的 bean 时出错:注入自动装配 依赖失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:不能 自动装配字段:私有 org.hibernate.SessionFactory com.demo.scheduler.dao.HibernateDAO.sessionFactory;嵌套异常 是 org.springframework.beans.factory.BeanCreationException: 错误 创建 ServletContext 中定义的名称为“sessionFactory”的 bean 资源[/WEB-INF/applicationContext.xml]:init方法的调用 失败的;嵌套异常是 java.lang.NullPointerException at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:513) 在 org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:92) 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284) ... 29 更多原因: org.springframework.beans.factory.BeanCreationException:错误 创建名为“schedulerServiceImpl”的bean:注入自动装配 依赖失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:不能 自动装配字段:public com.demo.scheduler.dao.SchedulerDAO com.demo.scheduler.service.SchedulerServiceImpl.schedulerDAO;嵌套的 例外是 org.springframework.beans.factory.BeanCreationException: 创建名为“hibernateDAO”的 bean 时出错:注入自动装配 依赖失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:不能 自动装配字段:私有 org.hibernate.SessionFactory com.demo.scheduler.dao.HibernateDAO.sessionFactory;嵌套异常 是 org.springframework.beans.factory.BeanCreationException: 错误 创建 ServletContext 中定义的名称为“sessionFactory”的 bean 资源[/WEB-INF/applicationContext.xml]:init方法的调用 失败的;嵌套异常是 java.lang.NullPointerException at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) 在 org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) 在 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) 在 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) 在 org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) 在 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:269) 在 org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:871) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:813) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730) 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:485) ... 31 更多原因: org.springframework.beans.factory.BeanCreationException:不能 自动装配字段:public com.demo.scheduler.dao.SchedulerDAO com.demo.scheduler.service.SchedulerServiceImpl.schedulerDAO;嵌套的 例外是 org.springframework.beans.factory.BeanCreationException: 创建名为“hibernateDAO”的 bean 时出错:注入自动装配 依赖失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:不能 自动装配字段:私有 org.hibernate.SessionFactory com.demo.scheduler.dao.HibernateDAO.sessionFactory;嵌套异常 是 org.springframework.beans.factory.BeanCreationException: 错误 创建 ServletContext 中定义的名称为“sessionFactory”的 bean 资源[/WEB-INF/applicationContext.xml]:init方法的调用 失败的;嵌套异常是 java.lang.NullPointerException at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:513) 在 org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:92) 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284) ... 44 更多原因: org.springframework.beans.factory.BeanCreationException:错误 创建名为“hibernateDAO”的bean:注入自动装配 依赖失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:不能 自动装配字段:私有 org.hibernate.SessionFactory com.demo.scheduler.dao.HibernateDAO.sessionFactory;嵌套异常 是 org.springframework.beans.factory.BeanCreationException: 错误 创建 ServletContext 中定义的名称为“sessionFactory”的 bean 资源[/WEB-INF/applicationContext.xml]:init方法的调用 失败的;嵌套异常是 java.lang.NullPointerException at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) 在 org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) 在 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) 在 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) 在 org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:871) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:813) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730) 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:485) ... 46 更多原因: org.springframework.beans.factory.BeanCreationException:不能 自动装配字段:私有 org.hibernate.SessionFactory com.demo.scheduler.dao.HibernateDAO.sessionFactory;嵌套异常 是 org.springframework.beans.factory.BeanCreationException: 错误 创建 ServletContext 中定义的名称为“sessionFactory”的 bean 资源[/WEB-INF/applicationContext.xml]:init方法的调用 失败的;嵌套异常是 java.lang.NullPointerException at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:513) 在 org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:92) 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284) ... 57 更多原因: org.springframework.beans.factory.BeanCreationException:错误 创建 ServletContext 中定义的名称为“sessionFactory”的 bean 资源[/WEB-INF/applicationContext.xml]:init方法的调用 失败的;嵌套异常是 java.lang.NullPointerException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) 在 org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) 在 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) 在 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) 在 org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:871) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:813) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730) 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:485)

【问题讨论】:

没有 Spring 3.3,所以我很难相信你会使用那个版本。您的帖子不完整发布您的配置,包括 web.xml。 我不确定它是否有效,只需添加 并检查一下。 不要忘记将&lt;mvc:annotation-driven&gt; 添加到您的配置中。 @Raju 那没必要。 component-scan 是通过包递归的。 @M.Deinum 对不起,我的错误。我使用的 Spring 是 3.1.4。我已经包含了 web.xml 和 dispatcher servlet。 或者去掉构造函数。无论哪种方式都应该有效。你仍然需要这个&lt;context:component-scan base-package="com.demo.scheduler" /&gt;。使用组件扫描时已经暗示了关于“”的注释。 【参考方案1】:

尝试在你的 web.xml 中添加 ContextLoaderListener:

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

【讨论】:

如果我添加 然后,我必须添加一个应用程序上下文。现在,我没有使用它。【参考方案2】:

如果发现我的错误。问题是该配置中没有任何东西可以实例化我的 DAO bean。因此,我在应用程序上下文中修改了我的“context:component-scan”元素,以获取我的 DAO。

<context:component-scan base-package="com.demo.scheduler">
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Service" />
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Repository" />
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

感谢@M.Deinum 和@SotiriosDelimanolis 的帮助

【讨论】:

以上是关于创建 Spring bean 时出错的主要内容,如果未能解决你的问题,请参考以下文章

Spring BeanCreationException:使用名称创建 bean 时出错

使用spring security的spring boot:创建名为“securityFilterChainRegistration”的bean时出错

Spring Boot - “创建名为 'entityManagerFactory' 的 bean 时出错” - 开始

Spring Boot - “创建名为 'entityManagerFactory' 的 bean 时出错” - 开始

创建名为“dataSource”+ Spring Boot + Hibernate 的 bean 时出错

OAUTH2 spring 创建名为“springSecurityFilterChain”的 bean 时出错