一、starter启动器相关
@Configuration //指定这个类是一个配置类
@ConfigurationOnXXX //在指定条件成立的情况下自动配置类生效
@AutoConfigureAfter //指定配置类的顺序
@Bean //给Spring容器中添加组件
@ConfigurationProperties //结合XXXProperties类来绑定配置
@EnableConfigurationProperties //生效某个配置类,并加入到容器中
二、自定义Starter
-
理解项目结构:
-
模块POM文件(启动器模块为空项目,主要依赖自动配置模块,主要代码也是写在自动配置模块)
(1)启动器模块pom文件
//引入自动配置模块
<dependency>
<groupId>com.demo.starter</groupId>
<artifactId>demo-spring-boot-starter-autoconfigure</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
(2)自动配置模块pom文件
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
</dependencies>
- 定义实体类映射配置信息(Properties),它决定了你在使用starter时,配置文件需要填写什么信息。
@ConfigurationProperties(prefix = "demo")
public class DemoProperties {
private String name;
private String msg;
//setter和getter省略不写
}
如上,你的实体类映射配置信息是这样的,则在使用starter时,在配置文件则那样进行设置。
- 添加一个service类,这个service提供给集成该starter的业务方调用。
public class DemoService {
@Autowired
private DemoProperties demoProperties;
public DemoProperties getDemoProperties() {
return demoProperties;
}
public void setDemoProperties(DemoProperties demoProperties) {
this.demoProperties = demoProperties;
}
public String sayHello(){
return demoProperties.getName()+"111111"+demoProperties.getMsg();
}
}
- 添加一个自动配置类
@Configuration
//引入实体映射配置信息
@EnableConfigurationProperties(DemoProperties.class)
public class DemoConfigure {
@Autowired
public DemoProperties properties;
@Bean
public DemoService demoService(){
DemoService demoService=new DemoService();
demoService.setDemoProperties(properties);
return demoService;
}
}
- 添加spring.factories文件(resources/META-INF/spring.factories)
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.demo.starter.DemoConfigure
- 将启动器和自动配置安装到Maven
三、创建新项目进行starter使用
- pom文件添加stater坐标
<dependency>
<groupId>com.demo.starter</groupId>
<artifactId>hello-demo-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
-
properties配置文件填写信息
-
controller层
@RestController
public class helloController {
//引入starter的service方法
@Autowired
private DemoService demoService;
@GetMapping("/hello")
public String hello() {
return demoService.sayHello();
}
}
- 测试
四、参考博文
参考地址1:https://blog.csdn.net/weixin_38657051/article/details/97487721?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_baidulandingword-1&spm=1001.2101.3001.4242
参考地址2:
http://www.manongjc.com/detail/15-odbdmxayybdddtf.html
参考地址3:
https://cloud.tencent.com/developer/article/1415098