Spring 中最简单的自定义注解的方式就是使用现有的注解,标注在自定义的注解之上,复用原注解的能力。
/**
* 自定义注解,继承自 @Component
*
* @author ConstXiong
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Component
public @interface CustomComponent {
String value() default "";
}
/**
* 自定义 ComponentScan
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@ComponentScan
public @interface CustomComponentScan {
/**
* 别名
*/
@AliasFor(annotation=ComponentScan.class, value="basePackages")
String[] v() default {};
}
/**
* 测试 Spring 自定义注解
*
* @author ConstXiong
*/
@CustomComponentScan(v="constxiong")
public class Test {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Test.class);
System.out.println(context.getBean("u", User.class));
}
}
微信小程序阅读
刷题面试、行情交流 加好友回 666 入群