目录
新建并打包starter启动器
启动器模块是一个空的jar文件,它仅提供辅助性的依赖管理,这些依赖可能用于自动装配或者其他类库
首先,我们建立一个maven项目spring-boot-starter
再新建一个springboot项目,spring-boot-starter-autoconfigure
我们首先在spring-boot-starter-autoconfigure项目中导入spring-boot-starter的依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
然后在spring-boot-starter项目中导入spring-boot-starter-autoconfigure的依赖
<dependencies>
<!-- 引入自动配置模块 -->
<dependency>
<groupId>com.lt</groupId>
<artifactId>spring-boot-starter-autoconfigure</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
编写代码,在spring-boot-starter-autoconfigure项目中编写一个自己的服务
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 配置类
// 前缀 lt.hello
@ConfigurationProperties(prefix = "lt.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
@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;
}
}
在resources/META-INF/spring.factories编写一个
然后分别使用maven来install我们的starter项目和autoconfigure项目
测试
1.找一个Springboot项目,导入我们自定义的starter启动器
<dependency>
<groupId>com.lt</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
2.搞一个Controller接口
@RestController
public class HelloController {
@Autowired
HelloService helloService;
@RequestMapping("/h1")
public String hello(){
return helloService.sayHello("sss");
}
}
3.编写配置文件
lt.hello.prefix="ppp"
lt.hello.suffix="sss"
4.启动项目,测试结果