怎么實(shí)現(xiàn)自己的starter累驮?
原理淺談
從總體上來(lái)看擎析,無(wú)非就是將Jar包作為項(xiàng)目的依賴引入工程幸海。而現(xiàn)在之所以增加了難度蜜自,是因?yàn)槲覀円氲氖荢pring Boot Starter诫肠,所以我們需要去了解Spring Boot對(duì)Spring Boot Starter的Jar包是如何加載的司澎?下面我簡(jiǎn)單說(shuō)一下。
SpringBoot 在啟動(dòng)時(shí)會(huì)去依賴的 starter 包中尋找 /META-INF/spring.factories 文件栋豫,然后根據(jù)文件中配置的路徑去掃描項(xiàng)目所依賴的 Jar 包挤安,這類似于 Java 的 SPI(JavaSPI 實(shí)際上是“基于接口的編程+策略模式+配置文件”組合實(shí)現(xiàn)的動(dòng)態(tài)加載機(jī)制。) 機(jī)制笼才。
實(shí)現(xiàn)自動(dòng)配置
1.新建一個(gè)Spring Boot工程漱受,命名為spring-boot-starter-hello,pom.xml依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.新建HelloProperties類骡送,定義一個(gè)hello.msg參數(shù)(默認(rèn)值World0合邸)。
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.自動(dòng)配置類虐先,可以理解為實(shí)現(xiàn)自動(dòng)配置功能的一個(gè)入口。
@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.項(xiàng)目到這里就差不多了篮愉,不過(guò)作為依賴腐芍,最好還是再做一下收尾工作
- 刪除自動(dòng)生成的啟動(dòng)類SpringBootStarterHelloApplication
- 刪除resources下的除META-INF目錄之外的所有文件目錄
- 刪除spring-boot-starter-test依賴并且刪除test目錄
- 執(zhí)行mvn install將spring-boot-starter-hello安裝到本地
2、隨便新建一個(gè)Spring Boot工程试躏,引入spring-boot-starter-hello依賴猪勇。
idea引入新的依賴,重新導(dǎo)入pom文件颠蕴,如果找不到可能是mvn intall 到本地包的.m2文件里路徑不對(duì)
<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.reibang.com/p/59dddcd424ad
解決中文亂碼解決:https://www.cnblogs.com/yueshutong/p/10703561.html