strtus中action注入spring bean


Action 中注入Spring 管理的Bean

ProductAction 是一个 Action,处理页面的请求,其中的save()方法使用到了业务层 ProductService对象,Spring 管理这个对象,所以涉及到 Action 中注入 Spring 管理的bean的问题。

记得导入spring整合structs2 的jar包 struts2-spring-plugin-2.3.31.jar
下面介绍两种注入方式

package com.jxust.ssh.action;
..
public class ProductAction extends ActionSupport implements ModelDriven<Product> {
    .
    .
    private ProductService produceService;

    public void setProduceService(ProductService produceService) {
        this.produceService = produceService;
    }

    public String save(){
        //这里需要用到ProductService对象
        produceService.save(product);
        return "index";
    }
}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

注入方法一(Action由Structs管理)

struts.xml 文件中,Action 的 class 为该 Action 的类路径,而在 Spring配置文件中不需要添加 ProductAction 的bean配置。当我们使用Action类时,由于 produceService 已经配置了相关的bean,所以会自动装配。

structs2中的配置

structs2配置Action的文件

struts.xml

<action name="product_*" class="com.jxust.ssh.action.ProductAction" method="{1}">
            <result name="index">index.jsp</result>
        </action > 
  
  
  • 1
  • 2
  • 3

类名使用完整路径class="com.jxust.ssh.action.ProductAction"

spring中的配置

spring的配置bean的文件

applicationContext.xml

    <!-- 配置业务层的类 -->
    <bean id="produceService" class="com.jxust.ssh.service.ProductService">
        ...
    </bean>
  
  
  • 1
  • 2
  • 3
  • 4

bean 的 id 值必须和 Action 中的变量名相同

private ProductService produceService;
//两者的名称要一一对应
<bean id="produceService".....
  
  
  • 1
  • 2
  • 3

注入方法二(Action由Spring管理)

struts.xml在配置 ProductAction 时,需要将class 名称和 Spring 配置文件中的相对应的ProductAction 的bean的 Id 的 名称保持一致,系统即可通过Spring来装配和管理Action。

建议使用这种方式,便于使用AOP管理

structs2中的配置

structs2配置Action的文件

struts.xml

    <action name="product_*" class="productActionBean" method="{1}">
            <result name="index">index.jsp</result>
        </action > 
  
  
  • 1
  • 2
  • 3

class的路径设置成spring 配置的bean的名称class="productActionBean"

struts.xml里action的class应写成spring里对应bean的id 。只有这样spring容器才会自动的将papermanager注入

spring中的配置

spring的配置bean的文件

applicationContext.xml

    <!-- 配置Action 的类 -->
    <bean id="productActionBean" class="com.jxust.ssh.action.ProductAction" scope="prototype">
        <property name="produceService" ref="productServiceBean"></property>
    </bean>

    <!-- 配置业务层的类 -->
    <bean id="productServiceBean" class="com.jxust.ssh.service.ProductService">
        ..
    </bean>
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

手动配置 ProductAction 中 ProductService 对象的注入,命名bean的名称为 productActionBean
spring中bean默认为单例的,要改为scope=”prototype”多例

参考

sun_zhicheng的博客http://blog.csdn.net/sun_zhicheng/article/details/24232129

猜你喜欢

转载自blog.csdn.net/qq_38949960/article/details/86301045