@Autowiring不在Field Level工作

时间:2011-07-18 20:26:04

标签: java spring spring-mvc autowired

@Autowiring无法处理字段并且正在获取:

错误:

         SEVERE: StandardWrapper.Throwable
        org.springframework.beans.factory.BeanCreationException: 
    Error creating bean with name 'contactController': 
    Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private net.viralpatel.contact.service.ContactService net.viralpatel.contact.controller.ContactController.contactService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contactServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private net.viralpatel.contact.dao.ContactDAO net.viralpatel.contact.service.ContactServiceImpl.contactDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contactDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory net.viralpatel.contact.dao.ContactDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool
            at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
            at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
            at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
            at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
            at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
            at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
            at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
            at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
            at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442)
            at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458)
            at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339)
            at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306)
            at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
            at javax.servlet.GenericServlet.init(GenericServlet.java:160)
            at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1201)
            at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1114)
            at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1021)
            at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4957)
            at org.apache.catalina.core.StandardContext$3.call(StandardContext.java:5284)
            at org.apache.catalina.core.StandardContext$3.call(StandardContext.java:5279)
            at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
            at java.util.concurrent.FutureTask.run(FutureTask.java:138)
            at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
            at java.lang.Thread.run(Thread.java:662)

我的web.xml是

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Spring3-Hibernate</display-name>
  <welcome-file-list>
    <welcome-file>list.html</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

我的spring-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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <context:annotation-config />
    <context:component-scan base-package="net.viralpatel.contact" />

    <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="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven />
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>

我的控制器是

    package net.viralpatel.contact.controller;

import java.util.Map;

import net.viralpatel.contact.form.Contact;
import net.viralpatel.contact.service.ContactService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class ContactController {

    @Autowired
    private ContactService contactService;

    @RequestMapping("/index")
    public String listContacts(Map<String, Object> map) {

        map.put("contact", new Contact());
        map.put("contactList", contactService.listContact());

        return "contact";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("contact")
    Contact contact, BindingResult result) {

        contactService.addContact(contact);

        return "redirect:/index";
    }

    @RequestMapping("/delete/{contactId}")
    public String deleteContact(@PathVariable("contactId")
    Integer contactId) {

        contactService.removeContact(contactId);

        return "redirect:/index";
    }
}

我的服务类是

package net.viralpatel.contact.service;

import java.util.List;

import net.viralpatel.contact.form.Contact;

public interface ContactService {

    public void addContact(Contact contact);
    public List<Contact> listContact();
    public void removeContact(Integer id);
}

服务类impl是

package net.viralpatel.contact.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.viralpatel.contact.dao.ContactDAO;
import net.viralpatel.contact.form.Contact;

@Service
public class ContactServiceImpl implements ContactService {

    @Autowired
    private ContactDAO contactDao;

    @Transactional
    public void addContact(Contact contact) {
        contactDao.addContact(contact);
    }

    @Transactional
    public List<Contact> listContact() {
        return contactDao.listContact();
    }

    @Transactional
    public void removeContact(Integer id) {
        contactDao.removeContact(id);
    }
}

我正在努力让@Autowiring工作,但它无法正常工作,有什么建议或线索可以解决它的工作方式吗?

5 个答案:

答案 0 :(得分:8)

您的例外情况很明确:

  

java.lang.NoClassDefFoundError:org / apache / commons / pool / impl / GenericObjectPool

这意味着您的类路径中没有commons-pool.jar。添加它。 (在WEB-INF/lib

答案 1 :(得分:1)

问题不是自动装配,而是NoClassDefFound:

  

注入自动连接的依赖项失败;嵌套异常是......
  在ServletContext资源[/WEB-INF/spring-servlet.xml]中定义名称为'sessionFactory'的bean创建错误:bean的初始化失败; 嵌套异常是java.lang.NoClassDefFoundError:org / apache / commons / pool / impl / GenericObjectPool

确保commons-pool的JAR在类路径上。

答案 2 :(得分:1)

使用网络应用程序,在类路径中使用jar是不够的。它也必须在正确的位置。确保jar位于WEB-INF/lib目录中,并且弹簧罐也是如此。如果您将其中一个置于容器的lib目录中,则可能会遇到类加载器问题。

通常,容器安装和webapp中的每个lib目录都有一个单独的类加载器,它们按层次结构组织。如果父类加载器中的类引用了子类中的类,您将看到此问题。

我的规则是只将事物放在WEB-INF/lib中。只有一次我看到了一个很好的理由来改变,既不添加也不删除也不升级任何容器lib目录的内容。

答案 3 :(得分:0)

我认为这是来自here的示例我可以毫无问题地运行此示例。 此示例使用maven。确保你的pom.xml中有这个

<dependency>
  <groupId>commons-pool</groupId>
  <artifactId>commons-pool</artifactId>
  <version>20030825.183949</version>
</dependency>

可能是因为它的旧版本没有实现类?另外,当你解压缩你的commons-pool.jar时(你提到了common-pool.jar,猜猜拼写错误?)你看到里面有GenericObjectPool.class吗?

答案 4 :(得分:0)

这是由于注入自动连接的依赖项失败,即pom.xml中的hibernate-entitymanager bean

在pom.xml中添加以下依赖项:

hibernate-entitymanager / 3.2.0.ga jar file

再次mvn clean install然后通过以下命令运行:

mvn org.mortbay.jetty:maven-jetty-plugin:run 

通过命令提示符避免丢失与java路径相关的异常