您好,欢迎来到暴趣科技网。
搜索
您的当前位置:首页Spring 如何自定义注解?

Spring 如何自定义注解?

来源:暴趣科技网

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));
    }
}

 

 


【Java面试题与答案】整理推荐

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baoquwan.com 版权所有 湘ICP备2024080961号-7

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务