學習spring-boot-starter自定義及應用

spring-boot-starter案例

通過下載以上附件,裏面是2個idea項目,其中spring-boot-08-starter是自定義,spring-boot-08-starter-test是對該starter的應用,我們今天重點來分析spring-boot-08-starter自定義這個項目。

該項目分爲2個模塊atguigu-spring-boot-starter和atguigu-spring-boot-starter-autoconfigurer。衆所周知,springboot的starter自定義規則是xxx-spring-boot-starter,atguigu-spring-boot-starter這個模塊是一個簡單的maven工程,只是描述xxx-spring-boot-starter的依賴關係,實現功能都是在atguigu-spring-boot-starter-autoconfigurer裏面來做的。這樣可以確保用戶需要使用這個功能時,只需要引入xxx-spring-boot-starter這個依賴就可以,不需要去擔心該功能依賴的其他模塊。

atguigu-spring-boot-starter的pom.xml文件內容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.atguigu.starter</groupId>
    <artifactId>atguigu-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--引入啓動器-->
    <dependencies>
        <!--引入自動配置模塊-->
        <dependency>
            <groupId>com.atguigu.starter</groupId>
            <artifactId>atguigu-spring-boot-starter-autoconfigurer</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>

接着我們來分析atguigu-spring-boot-starter-autoconfigurer是如何實現的

該模塊有個主要實現類,該類是功能自動注入,如實現HelloService自動實例化並加入到spring容器中

@Configuration
@ConditionalOnWebApplication  //如果是web應用,該配置生效
@EnableConfigurationProperties(HelloProperties.class)//使該HelloProperties.class配置文件生效
public class HelloServiceAutoConfiguration {
    @Autowired
    HelloProperties helloProperties;
    @Bean
    public HelloService helloService(){
        HelloService helloService=new HelloService();
        helloService.setHelloProperties(helloProperties);
        return helloService;
    }
}

那系統又是如何啓動這個類,需要在根路徑下META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.atguigu.starter.HelloServiceAutoConfiguration

通過springboot啓動時,會自動加載該文件下的內容,至此HelloService 對象已經被實例化到spring容器中

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章