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掃描到,並注入容器內。