我正在学习@Resource,java中的@Resources注入。 Oracle文档和其他一些站点正在使用@Resource注释解释字段,方法和类资源注入,但是我找不到使用@Resources注释的多类资源注入的帮助 - 实际上我想知道@Resources注释在类上声明的多个资源课堂上会用到什么? 我在其他网站上的oracle文档中看到的示例如下:
@Resources({
@Resource(name="myMessageQueue",
type="javax.jms.ConnectionFactory"),
@Resource(name="myMailSession",
type="javax.mail.Session")
})
public class SomeMessageBean {
...
}
但是我将如何在类体中使用myMessageQueue和myMailSession?那么任何人都可以通过@Resources注释来解释类体实现或示例方法实现,以显示上述声明资源的用法吗?
答案 0 :(得分:0)
基本上,@Resources
只是一个资源数组,并在运行时将该数组内的资源注入到类中。
package javax.annotation;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
/**
* This class is used to allow multiple resources declarations.
*
* @see javax.annotation.Resource
* @since 1.6, Common Annotations 1.0
*/
@Documented
@Retention(RUNTIME)
@Target(TYPE)
public @interface Resources {
/**
* Array used for multiple resource declarations.
*/
Resource[] value();
}
修改强> 以下代码来自org.apache.cxf.common.injection.ResourceInjector
的实现 79: // Implementation of org.apache.cxf.common.annotation.AnnotationVisitor
80:
81: public final void visitClass(final Class<?> clz, final Annotation annotation) {
82:
83: assert annotation instanceof Resource || annotation instanceof Resources : annotation;
84:
85: if (annotation instanceof Resource) {
86: injectResourceClassLevel(clz, (Resource)annotation);
87: } else if (annotation instanceof Resources) {
88: Resources resources = (Resources)annotation;
89: for (Resource resource : resources.value()) {
90: injectResourceClassLevel(clz, resource);
91: }
92: }
93:
94: }
你可以在第89行看到,它遍历Resources数组并注入Resources。
顺便说一句,您可以通过Resource[] resoruces = CLASS_NAME.class.getAnnotation(Resources.class).value();