Question

I want to make a web application based on struts2 and spring. First of all, I tested if @Autowired does work on struts2. But it does not, dataSource is null. I have no idea how I can fix it. Please give me an infomation for it.

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>
Was it helpful?

Solution

To make @Autowired work in your struts application you need to the given things:

Make sure you have the struts2 and spring plugin in your classpath.

Put the following line in strtus.xml

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

Configure the Action classes in xml file of spring

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

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

</bean>

And give the bean id in struts.xml file instead of giving the action class

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

For more information consult http://struts.apache.org/release/2.2.x/docs/spring-and-struts-2.html and http://struts.apache.org/release/2.2.x/docs/spring-plugin.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top