目录
注解说明
- 元注解:可以注解到别的注解上的注解,所以元注解首先基于条件@Target({ElementType.TYPE}) ,目标使用在类文件上 。
- 组合注解:连个元注解组合在一起的注解,注解A使用了注解B,那么注解A就叫组合注解,注解A会继承注解B的功能。
源代码
springBoot的入口注解@SpringBootApplication是一个组合注解,由注解@EnableAutoConfiguration、@SpringBootConfiguration,@ComponentScan,三个注解组成,功能继承了三个注解的功能。SpringBootApplication源码
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package org.springframework.boot.autoconfigure; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.AutoConfigurationExcludeFilter; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.TypeExcludeFilter; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.FilterType; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.core.annotation.AliasFor; @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration // 元注解 @EnableAutoConfiguration // 元注解 @ComponentScan( // 元注解 excludeFilters = {@Filter( type = FilterType.CUSTOM, classes = {TypeExcludeFilter.class} ), @Filter( type = FilterType.CUSTOM, classes = {AutoConfigurationExcludeFilter.class} )} ) public @interface SpringBootApplication { @AliasFor( annotation = EnableAutoConfiguration.class ) Class<?>[] exclude() default {}; @AliasFor( annotation = EnableAutoConfiguration.class ) String[] excludeName() default {}; @AliasFor( annotation = ComponentScan.class, attribute = "basePackages" ) String[] scanBasePackages() default {}; @AliasFor( annotation = ComponentScan.class, attribute = "basePackageClasses" ) Class<?>[] scanBasePackageClasses() default {}; }
使用范例
组合注解可以将多个元注解的功能集中到一个注解上 ,方便使用,简化代码。 写一个配置文件MyConfiguration将@Configuration 、@ComponentScan 两个注解组合在一起
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration //1元注解 @ComponentScan //2元注解 public @interface MyConfiguration { String[] value() default {}; //3 }
配置类使用注解
@MyConfiguration("springboot.annotation")//1使用自定义注解扫描文件夹,加载文件 public class DemoConfig { }
写一个TestBean放在 springboot.annotation下
@Service public class DemoService { public void outputResult(){ System.out.println("从组合注解配置照样获得的bean"); } }
Main方法测试
public class Main {public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class); DemoService demoService = context.getBean(DemoService.class); demoService.outputResult();//输出:从组合注解配置照样获得的bean context.close(); }