在Spring中自定義注解


Spring如何讀取注解信息,然后 注入到IOC容器里面

//增加Target注解,這個注解標注我們定義的注解是可以作用在類上還是方法上還是屬性上面
@Target({ ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface MyComponent {
    String value() default "";
}

@Retention注解:作用是定義被它所注解的注解保留多久,一共有三種策略,SOURCE 被編譯器忽略,CLASS注解將會被保留在Class文件中,但在運行時並不會被VM保留。這是默認行為,所有沒有用Retention注解的注解,都會采用這種策略。RUNTIME  報留至運行時。所以我們可以通過反射去獲取注解信息。

使用:

@Configuration
public class ComponentAnnotationTest {
  public static void main(String[] args) {
    AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
    annotationConfigApplicationContext.register(ComponentAnnotationTest.class);
    annotationConfigApplicationContext.refresh();
    InjectClass injectClass = annotationConfigApplicationContext.getBean(InjectClass.class);
    injectClass.print();
  }
  @MyComponent
  public static class InjectClass {
    public void print() {
        System.out.println("hello world");
    }
  }
}

@MyComponent 注解的類,也被Spring加載進來了,而且可以當成普通的JavaBean正常的使用。查看Spring的源碼會發現,Spring是使用ClassPathScanningCandidateComponentProvider掃描package。

Spring在掃描類信息的使用只會判斷被 @Component注解的類,所以任何自定義的注解只要帶上 @Component(當然還要有 String value() default "";的方法,因為Spring的Bean都是有beanName唯一標示的),都可以被Spring掃描到,並注入容器內。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM