1

我想制作一个基于struts2 和spring 的web 应用程序。首先,我测试了@Autowired 是否在struts2 上工作。但事实并非如此,dataSource 为空。我不知道如何解决它。请给我一个信息。

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;
    }
}

应用程序上下文.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>
4

1 回答 1

2

@Autowired在你的 struts 应用程序中工作,你需要给定的东西:

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

将以下行放入strtus.xml

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

配置Action classesspring的in xml文件

<bean id="editAction" class="org.apache.struts.edit.action.EditAction" >

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

</bean>

并在文件中给出 bean idstruts.xml而不是给出动作类

<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/弹簧插件.html

于 2014-01-06T04:42:41.383 回答