The*_*eLQ 12 java spring annotations
在我的项目中,有一个所有客户端类都扩展的公共基类.这有一个@Autowired字段,需要由Hibernate注入.这些都在另一个具有@Autowired基类集合的类中组合在一起.
为了减少客户端代码的样板,我试图让@Component继承.由于@Component默认情况下不这样做(显然它曾经用过),我创建了这个变通方法注释
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component
@Inherited
public @interface InheritedComponent {
}
Run Code Online (Sandbox Code Playgroud)
...并用它注释基类.它不漂亮但我希望它会起作用.不幸的是它没有,这真让我感到困惑,因为@Inherited应该让它发挥作用
有没有其他方法可以继承@Component?或者我只是要说任何扩展基类的类都需要这个样板?
问题是Component注释类型本身需要标记@Inherited.
您的@InheritedComponent注释类型由任何扩展超类的类正确继承,该超类被标记为@InheritedComponent- 但它不会继承@Component.这是因为你@Component的注释,而不是父类型.
一个例子:
public class InheritedAnnotationTest {
@InheritedComponent
public static class BaseComponent {
}
public static class SubClass extends BaseComponent {
}
public static void main(String[] args) {
SubClass s = new SubClass();
for (Annotation a : s.getClass().getAnnotations()) {
System.out.printf("%s has annotation %s\n", s.getClass(), a);
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
class brown.annotations.InheritedAnnotationTest $ SubClass有注释@ brown.annotations.InheritedComponent()
换句话说,当解析类具有的注释时,注释的注释不会被解析 - 它们不适用于类,只适用于注释(如果这是有意义的).
我通过创建自己的注释(heritable)然后自定义类路径扫描来处理这个问题:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component
@Inherited
public @interface BusinessService {
}
Run Code Online (Sandbox Code Playgroud)
Spring配置看起来像这样:
<context:component-scan base-package="io.bar">
<context:include-filter type="annotation"
expression="io.bar.core.annotations.BusinessService" />
</context:component-scan>
Run Code Online (Sandbox Code Playgroud)
来自Spring doc 5.10.3使用过滤器来自定义扫描
| 归档时间: |
|
| 查看次数: |
11969 次 |
| 最近记录: |