第一步:在web.xml中加入下面的listener
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> <!-- 默认去这个地方找 spring的配置文件并加载 default: /WEB-INF/applicationContext.xml --> </listener> <!--整个应用的参数配置,上面的listener启动时会去读这个配置--> <context-param> <param-name>contextConfigLocation</param-name> <!-- <param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value> --> <param-value>classpath:beans.xml</param-value> </context-param>
先加入struts2-spring -plugin-2.1.6.jar
然后在Action前面就可以加@Component 了
@component("user")
public class UserAction extends ActionSupport{。。。省略。。。}
@Component("user") @Scope("prototype") public class UserAction extends ActionSupport { private String username; private String password; private String password2; private UserManager um; public UserManager getUm() { return um; } @Resource(name="userManager") public void setUm(UserManager um) { this.um = um; } @Override public String execute() throws Exception { User u = new User(); u.setUsername(username); u.setPassword(password); if(um.exists(u)) { return "fail"; } um.add(u); return "success"; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPassword2() { return password2; } public void setPassword2(String password2) { this.password2 = password2; }
<param-value>classpath:beans.xml</param-value>
),找到之后,初始化bean。这样struts.xml 配置时 class="XXX",xxx就可以不是具体的Action类了,可以是和前面的name,也就是UserAction 前面的@Component("user")的user了。
通过配置ContextLoaderListener监听器,使容器启动时,自动加载applicationContext配置,
因为它实现了ServletContextListener这个接口,容器启动时会自动执行它实现的方法。