编写自定义starter
1.创建一个空项目,添加两个model,一个Maven作为启动器,一个springboot项目,作为依赖自动配置
2.编写starter自动配置器
创建一个方法:
//编写这样的程序,输出一个人名,可配置人名的前缀和后缀
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();
}
}
3.编写配置类
@ConfigurationProperties(prefix = "lss.hello")
//绑定配置spring.lss
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;
}
}
4.编写自动配置类
@Configuration
//添加配置类条件
@ConditionalOnWebApplication//是web应用才生效
@EnableConfigurationProperties(HelloProperties.class)//引入属性文件,使之生效
public class HelloServiceAutoconfiguration {
@Autowired
HelloProperties helloProperties;
//将方法helloservice注册在容器中
@Bean
//注册到容器中
public HelloService helloService(){
HelloService service = new HelloService();
service.setHelloProperties(helloProperties);//将属性文件添加上
return service;
}
}
5.在maven的pom文件中导入starter依赖
<dependencies>
<!--引入的自动配置-->
<dependency>
<groupId>com.lss</groupId>
<artifactId>lss-spring-boot-starter-autoconfigur</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
然后在右侧的Maven里两个项目的Lifestyle里双击install运行,添加进去。
测试自定义starter
1.创建控制器类
@RestController
public class HelloController {
@Autowired
HelloService helloService;
@RequestMapping("/aa")
public String test(){
return helloService.sayHello("刘思思");
}
}
并加入依赖
<!--引入自定义starter启动器-->
<dependency>
<groupId>com.lss.starter</groupId>
<artifactId>lss-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
2.编写配置文件,设置前后缀
lss.hello.prefix=hello
lss.hello.suffix=bye