一、说明
启动器模块是一个 空 jar 文件,仅提供辅助性依赖管理,这些依赖可能用于自动装配或者其他类库;
命名归约:
官方命名:
-
前缀:spring-boot-starter-xxx
-
比如:spring-boot-starter-web....
自定义命名:
-
xxx-spring-boot-starter
-
比如:mybatis-spring-boot-starter
二、编写启动器
1、在IDEA中新建一个空项目 spring-boot-starter-diy
2、新建一个普通Maven模块:sun-spring-boot-starter
3、新建一个Springboot模块:sun-spring-boot-starter-autoconfigure
4、点击apply即可,基本结构
5、在starter中导入autoconfigure的依赖
<!-- 启动器 -->
<dependencies>
<!-- 引入自动配置模块 -->
<dependency>
<groupId>com.sun</groupId>
<artifactId>kuang-spring-boot-starter-autoconfigure</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
6、将 autoconfigure 项目下多余的文件都删掉,Pom中只留下一个 starter,这是所有的启动器基本配置!
7、编写自定义服务
package com.sun;
public class HelloService {
HelloProperties helloProperties;
public HelloProperties getHelloProperties() {
return helloProperties;
}
public void setHelloProperties(HelloProperties helloProperties) {
this.helloProperties = helloProperties;
}
public String sayHello(String name){
return helloProperties.getPrefix() + name + helloProperties.getSuffix();
}
}
8、编写HelloProperties 配置类
package com.sun;
import org.springframework.boot.context.properties.ConfigurationProperties;
// 前缀 kuang.hello
@ConfigurationProperties(prefix = "sun.hello")
public class HelloProperties {
private String prefix;
private String suffix;
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
}
9、编写自定义配置类并注入bean,测试!
package com.sun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConditionalOnWebApplication //web应用生效
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {
@Autowired
HelloProperties helloProperties;
@Bean
public HelloService helloService(){
HelloService service = new HelloService();
service.setHelloProperties(helloProperties);
return service;
}
}
10、在resources中编写自己的 META-INF\spring.factories
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.sun.HelloServiceAutoConfiguration
11、编写完成后,安装到maven仓库中
三、新建项目测试自定义启动器
1、新建一个SpringBoot 项目
2、导入自定义启动器
<dependency>
<groupId>com.sun</groupId>
<artifactId>kuang-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
3、编写Controller 测试自定义接口
package com.sun.controller;
@RestController
public class HelloController {
@Autowired
HelloService helloService;
@RequestMapping("/hello")
public String hello(){
return helloService.sayHello("aaa");
}
}
4、编写配置文件 application.properties
sun.hello.prefix="aaa"
sun.hello.suffix="sss"
5、启动项目进行测试,结果成功 !