我想制作一个基于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>