Spring自定义注解加载和使用

kyaa111 3年前 ⋅ 638 阅读

Spring在扫描类信息的使用只会判断被@Component注解的类

所以任何自定义的注解只要带上@Component(当然还要有String value() default "";的方法,因为Spring的Bean都是有beanName唯一标示的)

都可以被Spring扫描到,并注入容器内

例: Spring官方的 @service 注解

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}

所以在部分业务场景下, 需要自定义注解并将被注解标记的类加入spring容器内的时候, 就可以将@Component注解加在自定义注解上