@autowired对struts2 + spring不起作用

时间:2014-01-06 02:44:50

标签: java spring struts2 autowired struts2-spring-plugin

我想基于struts2和spring创建一个Web应用程序。首先,我测试了@Autowired是否适用于struts2。但事实并非如此,dataSource为null。我不知道如何解决它。请给我一个信息。

HelloWorld.java

package example;
import java.sql.Connection;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.opensymphony.xwork2.ActionSupport;
@Component
public class HelloWorld extends ActionSupport {
    @Autowired
    private BasicDataSource dataSource;
    public String execute() throws Exception {
        Connection con = dataSource.getConnection();
        con.close();
        return SUCCESS;
    }
}

的applicationContext.xml

<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:mem" />
    <property name="maxActive" value="10" />
    <property name="username" value="sa" />
    <property name="password" value="" />
</bean>

<context:annotation-config />
<context:component-scan base-package="example" />

的web.xml

<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

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

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

struts.xml中

<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />

<package name="example" namespace="/example" extends="struts-default">
    <action name="HelloWorld" class="example.test.HelloWorld">
        <result>/example/HelloWorld.jsp</result>
    </action>
</package>

1 个答案:

答案 0 :(得分:2)

要使@Autowired在struts应用程序中正常工作,您需要完成以下任务:

确保你的类路径中有struts2和spring插件。

将以下行放在strtus.xml

<struts>
  <constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />
  ... 
</struts>

在spring

的xml文件中配置Action classes
<bean id="editAction" class="org.apache.struts.edit.action.EditAction" >

    <property name="editService" ref="editService" />

</bean>

并在struts.xml文件中提供bean id,而不是给出动作类

<action name="edit" class="editAction" method="input">
    <result name="input">/edit.jsp</result>
</action>  

有关详细信息,请参阅http://struts.apache.org/release/2.2.x/docs/spring-and-struts-2.htmlhttp://struts.apache.org/release/2.2.x/docs/spring-plugin.html