启动器模块是一个 空 jar 文件,仅提供辅助性依赖管理,这些依赖可能用于自动装配或者其他类库;
前缀:spring-boot-starter-xxx
比如:spring-boot-starter-web
自定义命名:xxx-spring-boot-starter
比如:mybatis-spring-boot-starter
编写启动器
新建空项目 spring-boot-starter-diy
新建Maven模块:lxs -spring-boot-starter
新建Springboot模块:lxs-spring-boot-starter-autoconfigure
![在这里插入图片描述
在starter 中 导入 autoconfigure 依赖!
<dependencies>
<dependency>
<groupId>com.kuang</groupId>
<artifactId>lxs-spring-boot-starter-autoconfigure</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
autoconfigure 项目多余的文件都删掉,Pom。xml中留下一个 starter,这是启动器基本配置
编写自己的服务
package com.kuang;
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();
}
}
编写HelloProperties 一个配置类
package com.lxs;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "lxs.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;
}
}
编写自动配置类并注入bean
package com.lxs;
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
@EnableConfigurationProperties(LxsProperties.class)
public class LxServiceAutoConfiguration {
@Autowired
LxsProperties lxsProperties;
@Bean
public LxsService lxsService(){
LxsServiceservice = new LxsService();
service.setHelloProperties(helloProperties);
return service;
}
}
在resources编写自己的 META-INF\spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\com.lxs.LxsServiceAutoConfiguration
编写完成后,可以安装到maven仓库中,新建项目测试写的启动器
1、新建SpringBoot 项目
2、导入自己写的启动器
<dependency>
<groupId>com.lxs </groupId>
<artifactId>lxs-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
3、编写HelloController 测试自己写的接口
package com.lxs.controller;
@RestController
public class LxsController {
@Autowired
LxsService lxsService;
@RequestMapping("/hello ! sb")
public String lxs(){
return helloService.sayHello("sb");
}
}