Spring Boot 自動配置之組合註解

SpringBoot應用開發,會大量的使用註解,有些註解會常常一塊兒使用,若是能經過一個組合註解進行包裝則可以簡化代碼,而且還會避免由於少了某些註解而報錯java

1、 常見的組合註解

1. @SpringBootApplication

該註解是SpringBoot項目的核心註解,該註解包含:git

  • @SpringBootConfiguration
  • @EnableAutoConfiguration
  • @ComponentScan

@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

2. @Configuration

該註解包含@Component註解,該註解不單標註該類是一個配置類,並且聲明該類是一個Beanspringboot

3. @Enable*

@Enable* 類的註解都有一個@Import註解,該註解是用來導入配置類的,其實就是導入了一些自動配置的Bean,有如下三類:spring-boot

  1. 直接導入配置類測試

    導入一個有 @Configuration的Beancode

  2. 依據條件選擇配置類

    導入一個實現了ImportSelector接口的配置類

  3. 動態註冊Bean

    導入一個實現了ImportBeanDefinitionRegistrar接口的配置類

本文不作深刻探討,會另出一篇關於@Import的使用

2、自定義組合註解

咱們在配置類上加@ComponentScan時還會寫@Configuration咱們能夠寫一個組合註解

  1. 組合註解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
@ComponentScan
public @interface ComponentScanConfig {
    
    //這個必須寫,覆蓋@ComponentScan的註解value的值
    String[] value() default {};
}

【注】String[] value() default {}; 是爲了覆蓋@ComponentScan的註解value的值

  1. service
public class CombinationAnnotationTestService {

    public void doSth() {
        System.out.println("doSth....");
    }
}
  1. 配置類
@ComponentScanConfig("com.jiuxian.combination")
public class CombinationAnnotationConfig {

    @Bean
    public CombinationAnnotationTestService combinationTestService() {
        return new CombinationAnnotationTestService();
    }
}
  1. 測試

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

}
  1. 結果
doSth....

3、GitHub源碼

GitHub源碼

相關文章
相關標籤/搜索