[Struts2] struts2 @Inject 注解

struts2 @Inject 注解  

2010-12-14 21:30:54|  分类: struts2 |  标签:inject  struts2  |字号 订阅

@Inject 注解在struts2 框架中被大量使用, @Inject 注解可在方法, 构造函数, 字段, 参数上使用

来看下struts2 的   @Inject定义
  @Target({METHOD, CONSTRUCTOR, FIELD, PARAMETER})
  @Retention(RUNTIME)
public @interface Inject {

  /**
   * Dependency name. Defaults to {@link Container#DEFAULT_NAME}.
   */
  String value() default DEFAULT_NAME;

  /**
   * Whether or not injection is required. Applicable only to methods and
   * fields (not constructors or parameters).
   */
  boolean required() default true;
}


现假设如下场景, 有一个获取数据库连接的公用类  ConnectionUtil
每个Action中都需要使用该工具类, 要实现这个功能的方法很多, 现在来看看用@Inject 注解怎么实现

1. 定义一个Action父类, ConnectionAction

使用method注入:
ConnectionAction{
  protected ConnectionUtil connectionUtil;
  @Inject
  public void setConnectionUtil(@Inject(value="connectionUtil") ConnectionUtil connectionUtil) // 参数中不使用注解, 则connectionUtil组件名称默认是 default
  {
      this.connectionUtil = connectionUtil;
  }
}

或者使用Filed注入
ConnectionAction{
  @Inject(value="connectionUtil")
  protected ConnectionUtil connectionUtil;
}


2. 配置struts.xml文件
   增加一行配置
   <bean type="com.test.ConnectionUtil" name="connectionUtil" class="com.test.ConnectionUtil" />

3. 所有需要使用ConnectionUtil组件的action只要继承ConnectionAction即可

注: struts2 中, 一个类标记有 @Inject 注解, 在示例话这个类的时候struts2容器会将指定的参数注入
     具体参加  Container.java 接口的
   /**
     * Injects dependencies into the fields and methods of an existing object.
   */
    void inject(Object o);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值