@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);