SpringBoot(三)手寫starter pom自動配置


思想:主要是EnableAutoConfiguration在啟動的時候會掃描spring.factories並加載

 

1在resource下面新建META-INF/spring.factories

2在spring.factories中添加自動裝載的類

3其他項目引用既OK

 

1.新建一個starter的Maven項目A,pom文件修改

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example.start</groupId>
    <artifactId>spring-boot-starter-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
    <!--支持讀取配置文件屬性-->
      <dependency>
           <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-configuration-processor</artifactId>
          <optional>true</optional>
      </dependency>
  <!--需要改jar 才會自動加載enableautoconfiguration-->

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2.新建resource文件,META-INF/spring.factories文件

多個可這樣寫:(\表示換行可讀取到屬性)(,多個屬性分割)

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.example.start.demo.service.MyHelloConfiguration,\ com.example.start.demo.service.MyHelloConfiguration

3.新建MyHelloConfiguration配置類

@Configuration
public class MyHelloConfiguration { //當不存在HelloService時加載 @Bean @ConditionalOnMissingBean(HelloService.class) public HelloService test() { HelloService helloService = new HelloService(); helloService.setMsg("world"); return helloService; } }

 

public class HelloService {

    private String msg;

    public void setMsg(String msg) {
        this
                .msg = msg;
    }

    public String sayHello() {
        return "hello" + msg;
    }
}

 

 

 

4.在IDEA中Maven下執行install將jar包發布到本地倉庫

  

5在項目B中引入項目A新建的spring-boot-starter-demo.jar

   <dependency>
            <groupId>com.example.start</groupId>
            <artifactId>spring-boot-starter-demo</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

6項目B引用測試結果:

項目B調用項目A的service

啟動項目B設置application.properties文件debug=true,啟動輸出結果:

 

測試運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM