转载自:http://blog.csdn.net/wuyt2008/article/details/8237150
这里,还可以用spring的注解注入的方式进行注入。
导入的包和之前一样不变,web.xml不变
applicationContext.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <context:component-scan base-package="demo.myssh.business" />
- </beans>
struts.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
- "http://struts.apache.org/dtds/struts-2.3.dtd">
- <struts>
- <package name="mysshdemo" extends="struts-default">
- <action name="user" class="demo.myssh.action.UserAction">
- <result>/index.jsp</result>
- </action>
- </package>
- </struts>
UserAction.java
- package demo.myssh.action;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import com.opensymphony.xwork2.ActionSupport;
- import demo.myssh.business.UserService;
- public class UserAction extends ActionSupport {
- @Override
- public String execute() throws Exception {
- this.addActionMessage("UserAction working");
- // this.addActionMessage("hello world.");
- this.addActionMessage(userService.doing());// 修改下,确认注入成功。
- return ActionSupport.SUCCESS;
- }
- // 注入属性
- @Autowired
- private UserService userService;
- }
UserService.java
- package demo.myssh.business;
- import org.springframework.stereotype.Service;
- @Service
- public class UserService {
- public String doing()
- {
- return "UserService working.";
- }
- }
运行结果和之前的一样。
这样的注入方式可以省去一些代码,不需要大量的配置文件。
没有大量的配置文件,好处是省了不少代码,坏处是没有统一地方查看。
不过个人认为,如果采取这样的注入方式的话,不如直接把struts踢掉直接用spring3的mvc好了。