iteye_14486
iteye_14486
2010-12-02 16:11
浏览 327
已采纳

Spring注入action的Service为什么总是为空啊?

话不多说,上代码:

类Person,接口PersonDAO,接口PersonService略

实现类PersonDAOImpl:

package web.dao.impl;

import java.util.List;
import org.hibernate.LockMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import web.dao.PersonDAO;
import web.entity.Person;

/**
 * A data access object (DAO) providing persistence and search support for
 * Person entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see web.entity.Person
 * @author MyEclipse Persistence Tools
 */

public class PersonDAOImpl extends HibernateDaoSupport implements PersonDAO
{
    private static final Logger log = LoggerFactory.getLogger(PersonDAOImpl.class);
    // property constants
    public static final String PASSWORD = "password";

    protected void initDao() {
        // do nothing
    }

    public void save(Person transientInstance) {
        log.debug("saving Person instance");
        try {
            getHibernateTemplate().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }

    public void delete(Person persistentInstance) {
        log.debug("deleting Person instance");
        try {
            getHibernateTemplate().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    public Person findById(java.lang.String id) {
        log.debug("getting Person instance with id: " + id);
        try {
            Person instance = (Person) getHibernateTemplate().get(
                    "web.entity.Person", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public List findByExample(Person instance) {
        log.debug("finding Person instance by example");
        try {
            List results = getHibernateTemplate().findByExample(instance);
            log.debug("find by example successful, result size: "
                    + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }

    public List findByProperty(String propertyName, Object value) {
        log.debug("finding Person instance with property: " + propertyName
                + ", value: " + value);
        try {
            String queryString = "from Person as model where model."
                    + propertyName + "= ?";
            return getHibernateTemplate().find(queryString, value);
        } catch (RuntimeException re) {
            log.error("find by property name failed", re);
            throw re;
        }
    }

    public List findByPassword(Object password) {
        return findByProperty(PASSWORD, password);
    }

    public List findAll() {
        log.debug("finding all Person instances");
        try {
            String queryString = "from Person";
            return getHibernateTemplate().find(queryString);
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }

    public Person merge(Person detachedInstance) {
        log.debug("merging Person instance");
        try {
            Person result = (Person) getHibernateTemplate().merge(
                    detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(Person instance) {
        log.debug("attaching dirty Person instance");
        try {
            getHibernateTemplate().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public void attachClean(Person instance) {
        log.debug("attaching clean Person instance");
        try {
            getHibernateTemplate().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
}

这是myeclipse自己生成的也应该没有啥问题。

PersonServiceImpl:

package web.service.impl;

import web.dao.PersonDAO;
import web.entity.Person;
import web.service.PersonService;

public class PersonServiceImpl implements PersonService 
{
    private PersonDAO personDAO;

    public boolean equals(Object obj) {
        return personDAO.equals(obj);
    }

    public PersonDAO getPersonDAO() {
        return personDAO;
    }

    public void setPersonDAO(PersonDAO personDAO) {
        this.personDAO = personDAO;
    }

    public int hashCode() {
        return personDAO.hashCode();
    }

    public String toString() {
        return personDAO.toString();
    }

    @Override
    public void doSave(Person person) {
        personDAO.save(person);
    }

}

PersonAction:

package web.action;

import web.entity.Person;
import web.service.PersonService;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class PersonAction extends ActionSupport
{
    private String username;
    private String password;
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    
    private PersonService personService;
    
    public PersonService getPersonService() {
        return personService;
    }
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }
    
    public String doSave()
    {
        Person person = new Person();
        person.setUsername(username);
        person.setPassword(password);
        System.out.println(PersonDAO);/////////////////////////////////////////////////////////////这里是NULL NULL NULL 调了一天 要疯了
        personService.doSave(person);
        return SUCCESS;
    }

}

applicationContext.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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"  
    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/tx
                        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
                        http://www.springframework.org/schema/aop  
                        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName">
            <value>com.mysql.jdbc.Driver</value>
        </property>
        <property name="url">
            <value>jdbc:mysql://localhost:3306/test</value>
        </property>
        <property name="username">
            <value>root</value>
        </property>
        <property name="password">
            <value>1234</value>
        </property>
    </bean>
    
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <!-- <property name="configLocation"
            value="classpath:hibernate.cfg.xml">
        </property> -->
        <property name="dataSource" ref="dataSource"/>
        <property name="mappingResources">
            <list>
                <value>web/dao/hibmap/Person.hbm.xml</value>
                
            </list>
        </property>
        <property name="hibernateProperties">
          <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.che.provider_class">org.hibernate.che.HashtableCheProvider</prop>
            <prop key="hibernate.query.ftory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFtory</prop>
          </props>
        </property>
    </bean>
       
    <bean id="txManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true" propagation="SUPPORTS" />
            <tx:method name="find*" read-only="true" propagation="SUPPORTS" />
            <tx:method name="*" read-only="false" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>
       
    <aop:config>
        <aop:pointcut id="txDAO" expression="execution (* dao.*.*(..))" />
        <aop:advisor pointcut-ref="txDAO" advice-ref="txAdvice" />
    </aop:config>

    <!-- DAOs --> 
    <bean id="PersonDAOImpl" class="web.dao.impl.PersonDAOImpl" scope="singleton">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    
    <!-- Services -->
    <bean id="PersonServiceImpl" class="web.service.impl.PersonServiceImpl" scope="prototype">
        <property name="personDAO" ref="PersonDAOImpl"/>
    </bean>
    
    <!-- Actions -->
    <bean name="PersonAction" class="web.action.PersonAction" scope="prototype">
        <property name="personService" ref="PersonServiceImpl"/>
    </bean>   
    </beans>

web.xml:

<?xml version="1.0" encoding="UTF-8" ?> 
 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <context-param>
  <param-name>contextConfigLocation</param-name> 
  <param-value>/WEB-INF/classes/applicationContext.xml</param-value> 
 </context-param>

 <filter>
  <filter-name>struts2</filter-name> 
  <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> 
  </filter>
 <filter-mapping>
  <filter-name>struts2</filter-name> 
  <url-pattern>*.action</url-pattern> 
  </filter-mapping>
  <filter-mapping>
     <filter-name>struts2</filter-name> 
     <url-pattern>*.jsp</url-pattern>
  </filter-mapping>
  
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
  </listener>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file> 
  </welcome-file-list>
  </web-app>

  struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
   <constant name="struts.objectFactory" value="spring"></constant>
   
    <package name="default" namespace="/" extends="struts-default">
        <action name="PersonAction" class="web.action.PersonAction" method="doSave">
            <result name="success">/success.jsp</result>
        </action>
    </package>
</struts>    

这是错误:

 

java.lang.NullPointerException
    web.action.PersonAction.doSave(PersonAction.java:42)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    java.lang.reflect.Method.invoke(Method.java:597)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243)
    com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252)
    org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)

我不明白我的spring配置文件没有找到什么映射错误,而且action中,service中都有注入类的set方法,可是为什么是null值,高手请指教,不胜感激!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • weixin_42519569
    智百盛软件 2010-12-02 16:21
    已采纳

    额,老问题了

    struts.xml

    ->

    同时确认 struts2-spring-plugin.jar的存在。

    点赞 评论
  • nishinimas
    nishinimas 2010-12-02 16:24

    private PersonService personService;
    这里personService要和id里面定义的名字一样,你改过来试下




    点赞 评论

相关推荐