SpringBoot应用开发,会大量的使用注解,有些注解会常常一块儿使用,若是能经过一个组合注解进行包装则可以简化代码,而且还会避免由于少了某些注解而报错java
该注解是SpringBoot项目的核心注解,该注解包含:git
@SpringBootApplication 注解就有了自动配置功能 、扫描包功能。github
@EnableAutoConfiguration 让SpringBoot根据类路径中的jar包依赖为当前项目进行自动配置。例如,添加spring-boot-starter-web依赖,会自动添加tomcat和SpringMVC的依赖,SpringBoot 会对Tomcat和SpringMVC进行自动配置web
@ComponentScan 会自动扫描@SpringBootApplication所在类的同级包以及子包的Bean。因此建议入口类放在groupId+artifactId组合下,或者groupId下。spring
在SpringBoot项目启动类上用这三个注解替换@SpringBootApplication也是能够的tomcat
该注解包含@Component注解,该注解不单标注该类是一个配置类,并且声明该类是一个Beanspringboot
@Enable* 类的注解都有一个@Import注解,该注解是用来导入配置类的,其实就是导入了一些自动配置的Bean,有如下三类:spring-boot
直接导入配置类测试
导入一个有 @Configuration的Beancode
依据条件选择配置类
导入一个实现了ImportSelector接口的配置类
动态注册Bean
导入一个实现了ImportBeanDefinitionRegistrar接口的配置类
本文不作深刻探讨,会另出一篇关于@Import的使用
咱们在配置类上加@ComponentScan时还会写@Configuration咱们能够写一个组合注解
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration @ComponentScan public @interface ComponentScanConfig { //这个必须写,覆盖@ComponentScan的注解value的值 String[] value() default {}; }
【注】String[] value() default {}; 是为了覆盖@ComponentScan的注解value的值
public class CombinationAnnotationTestService { public void doSth() { System.out.println("doSth...."); } }
@ComponentScanConfig("com.jiuxian.combination") public class CombinationAnnotationConfig { @Bean public CombinationAnnotationTestService combinationTestService() { return new CombinationAnnotationTestService(); } }
(1)
public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(CombinationAnnotationConfig.class); CombinationAnnotationTestService service = context.getBean(CombinationAnnotationTestService.class); service.doSth(); context.close(); } }
(2)
@RunWith(SpringRunner.class) @SpringBootTest public class SpringbootAnnotationsApplicationTests { @Resource private CombinationAnnotationTestService combinationAnnotationTestService; @Test public void combinationTest() { combinationAnnotationTestService.doSth(); } }
doSth....