web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
spring:
<bean id="worEmprgAction" class="action.WorEmprgAction">
<property name="worEmprgService">
<ref bean="worEmprgService" />
</property>
</bean>
<bean id="worEmprgService" class="service.impl.WorEmprgService">
<property name="worEmprgDAO">
<ref bean="worEmprgDAO" />
</property>
</bean>
<bean id="worEmprgDAO" class="dao.WorEmprgDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
structs:
<package name="worEmprg" extends="struts-default">
<action name="worEmprgAction" class="action.WorEmprgAction">
<result name="success" type="redirect">/success.jsp</result>
<result name="failed" type="redirect">/failed.jsp</result>
</action>
</package>
action如下:
public class WorEmprgAction extends ActionSupport {
public String execute() throws Exception {
try{
worEmprgService.GetWorEmprgByPage();
return "success";
}
catch (Exception ex){
ex.printStackTrace();
return "failed";
}
}
private IWorEmprgService worEmprgService;
public IWorEmprgService getWorEmprgService() {
return worEmprgService;
}
public void setWorEmprgService(IWorEmprgService worEmprgService) {
this.worEmprgService = worEmprgService;
}
}
我在setWorEmprgService这里打了断点,启动tomcat的时候,这里注入执行了,但是我在浏览器中输入action地址,进入后worEmprgService为null,然后就报错java.lang.NullPointerException,请问应该怎么解决?
------解决方案--------------------
你的action不是spring生成的自然没注入,用spring生成struts2的action请在struts.xml中加上
<constant name="struts.objectFactory" value="spring"/>
再把<action name="worEmprgAction" class="action.WorEmprgAction">改成
<action name="worEmprgAction" class="worEmprgAction">用你spring声明的这action的名称
还有在spring配置中
<bean id="worEmprgAction" class="action.WorEmprgAction" scope="prototype">加上scope为prototype默认是单例那样会出现访问过就不能再用的情况