spring-boot引入mvn install打好包

怎么實(shí)現(xiàn)自己的starter?

原理淺談

從總體上來看,無非就是將Jar包作為項目的依賴引入工程。而現(xiàn)在之所以增加了難度,是因為我們引入的是Spring Boot Starter,所以我們需要去了解Spring Boot對Spring Boot Starter的Jar包是如何加載的?下面我簡單說一下。

SpringBoot 在啟動時會去依賴的 starter 包中尋找 /META-INF/spring.factories 文件,然后根據(jù)文件中配置的路徑去掃描項目所依賴的 Jar 包,這類似于 Java 的 SPI(JavaSPI 實(shí)際上是“基于接口的編程+策略模式+配置文件”組合實(shí)現(xiàn)的動態(tài)加載機(jī)制。) 機(jī)制。

實(shí)現(xiàn)自動配置

1.新建一個Spring Boot工程,命名為spring-boot-starter-hello,pom.xml依賴:

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.新建HelloProperties類,定義一個hello.msg參數(shù)(默認(rèn)值World!)。

public class HelloProperties {
    private String msg = "World!";
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
}

3.新建HelloService類,使用HelloProperties類的屬性

@Service
public class HelloService {
    @Autowired
    private HelloProperties helloProperties;
    public String sayHello(String name) {
        return "Hello " + name + " " + helloProperties.getMsg();
    }
}

4.自動配置類,可以理解為實(shí)現(xiàn)自動配置功能的一個入口。

@Configuration //定義為配置類
@ConditionalOnWebApplication //在web工程條件下成立
@EnableConfigurationProperties({HelloProperties.class}) //啟用HelloProperties配置功能,并加入到IOC容器中
@Import(HelloService.class) //導(dǎo)入HelloService組件
public class HelloAutoConfiguration {
}

5.在resources目錄下新建META-INF目錄,并在META-INF下新建spring.factories文件,寫入:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.hanxing.spirngboot.HelloAutoConfiguration

6.項目到這里就差不多了,不過作為依賴,最好還是再做一下收尾工作

  • 刪除自動生成的啟動類SpringBootStarterHelloApplication
  • 刪除resources下的除META-INF目錄之外的所有文件目錄
  • 刪除spring-boot-starter-test依賴并且刪除test目錄
  • 執(zhí)行mvn install將spring-boot-starter-hello安裝到本地
2、隨便新建一個Spring Boot工程,引入spring-boot-starter-hello依賴。

idea引入新的依賴,重新導(dǎo)入pom文件,如果找不到可能是mvn intall 到本地包的.m2文件里路徑不對

<dependency>
  <groupId>com.hanxing</groupId>
  <artifactId>spring-boot-starter-hello</artifactId>
   <version>0.0.1-SNAPSHOT</version>
</dependency>

在新工程中使用spring-boot-starter-hello的sayHello功能。

@SpringBootApplication
@Controller
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    @Autowired
    private HelloService helloService;
    @RequestMapping(value = "/sayHello")
    @ResponseBody
    public String sayHello(String name) {
        System.out.println(helloService.sayHello(name));
        return helloService.sayHello(name);
    }
}

參考文檔:http://www.itdecent.cn/p/59dddcd424ad
解決中文亂碼解決:https://www.cnblogs.com/yueshutong/p/10703561.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容