如何自定义一个Springboot-starter
1.首先在idea中创建一个Empty_project
2.然后在里面添加2个模块
1)starter模块(普通maven)
2)autoConfiguration模块(spring initializer)
3.在starter的pom文件中引入autoconfiguration模块的dependency
4.在autoConfiguration模块中添加模块的服务类
package com.shufang.starter.shufangspringbootstarterautoconfigurer;
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();
}
}
package com.shufang.starter.shufangspringbootstarterautoconfigurer;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "shufang.hello")
public class HelloProperties {
private String prefix;
private String suffix;
public HelloProperties() {
}
public HelloProperties(String prefix, String suffix) {
this.prefix = prefix;
this.suffix = 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;
}
}
package com.shufang.starter.shufangspringbootstarterautoconfigurer;
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
@EnableConfigurationProperties(HelloProperties.class)
@ConditionalOnWebApplication
public class HelloServiceAutoConfiguration {
@Autowired
HelloProperties helloProperties;
@Bean
public HelloService helloService() {
HelloService helloService = new HelloService();
helloService.setHelloProperties(helloProperties);
return helloService;
}
}
#最后,得在AutoConfiguration中添加com.shufang.starter.shufangspringbootstarterautoconfigurer.HelloServiceAutoConfiguration
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.shufang.starter.shufangspringbootstarterautoconfigurer.HelloServiceAutoConfiguration
5.通过maven的生命周期管理,install2个不同的模块到maven仓库中
结束语:届时完成starter的创建,然后在其他项目中可以引用了