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>
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
Configure the
Action classes
in xml file of springAnd give the bean id in
struts.xml
file instead of giving the action classFor 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