[英]Inject all beans with a specific annotation
I've been using Spring for decades, but never ran into this use-case before. 我已经使用Spring几十年了,但之前从未涉及过这个用例。
Is there a way to inject all the beans annotated with a specific annotation, eg all beans with @Service
or all with @CustomAnnotation
? 有没有办法注入所有使用特定注释注释的bean,例如所有带有
@Service
bean或者所有带有@CustomAnnotation
?
The only idea I have is to inject the context, get all the beans and filter manually. 我唯一的想法是注入上下文,获取所有 bean并手动过滤。 If this is the only way, does Spring expose a method that recursively scans a class hierarchy for (meta) annotations (as most Spring annotations can be used as meta-annotations)?
如果这是唯一的方法,那么Spring是否会公开一个递归扫描类层次结构以进行(元)注释的方法(因为大多数Spring注释可以用作元注释)?
The @ComponentScan
annotation specifies includeFilters
and excludeFilters
attributes. @ComponentScan
批注指定includeFilters
和excludeFilters
属性。
To scan only classes decorated with @Service
you could disable useDefaultFilters
and include only the Service
annotation : 要仅扫描用
@Service
修饰的类,可以禁用useDefaultFilters
并仅包含Service
注释:
@ComponentScan(useDefaultFilters = false,
includeFilters = @Filter(Service.class))
To scan only custom annotations, you could write a similary thing : 要仅扫描自定义注释,您可以编写类似的东西:
@ComponentScan(useDefaultFilters = false,
includeFilters = @Filter(CustomAnnotation.class))
As multiples classes are specified in value/classes
of @Filter
, a OR
logic is applied. 由于在
@Filter
value/classes
类中指定了多个类,因此应用OR
逻辑。
Note that the @Filter
annotation accepts class(es) as value/classes
attribute but these are interpreted by Spring according to the type
value of @Filter
. 注意
@Filter
注释接受class(es)作为value/classes
属性,但Spring会根据@Filter
的type
值来解释它们。
By default, type
has as value FilterType.ANNOTATION
. 默认情况下,
type
具有值FilterType.ANNOTATION
。
To filter on a specific annotation (as you in your case), this default value suits as you want to filter candidates on the annotation itself. 要过滤特定注释(在您的情况下),此默认值适合您要在注释本身上过滤候选项。
Here values defined in the FilterType enum class : 这里在FilterType枚举类中定义的值:
public enum FilterType {
ANNOTATION,
ASSIGNABLE_TYPE,
ASPECTJ,
REGEX,
CUSTOM
}
Note also that @Filter
works with classes/value
but not only. 还要注意
@Filter
适用于classes/value
而且适用于它。
You have indeed two alternative ways : 你确实有两种替代方式:
valuing the classes/value
attribute (as in your case) 评估
classes/value
属性(如您的情况)
valuing pattern
attribute. 评估
pattern
属性。
The first way expects to have as type
: ANNOTATION
, ASSIGNABLE_TYPE
or CUSTOM
. 第一种方式期望具有
type
: ANNOTATION
, ASSIGNABLE_TYPE
或CUSTOM
。
While the second way expects to have as type
: REGEX
or ASPECTJ
. 虽然第二种方式期望具有
type
: REGEX
或ASPECTJ
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.