1. 程式人生 > >SpringBoot編寫自定義Starter

SpringBoot編寫自定義Starter

this star pom.xml ring work image pty web ble

根據SpringBoot的Starter編寫規則,需要編寫xxxStarter依賴xxxAutoConfigurer,xxxStarter是一個空的jar,僅提供輔助性的依賴管理,引入其他類庫

1.建立一個empty工程,建立一個普通maven模塊xxxStarter,建立一個SpringBoot模塊xxxAutoConfigurer,前者依賴後者

2.xxxAutoConfigurer:

新建:HelloService:

public class HelloService {

    private HelloProperties helloProperties;

    public
void setHelloProperties(HelloProperties helloProperties) { this.helloProperties = helloProperties; } public HelloProperties getHelloProperties() { return helloProperties; } public String hello(){ return StringFormatter.format("%s:你好,%s歡迎光臨",helloProperties.getWeekend(),helloProperties.getName()).getValue(); } }

新疆:HelloProperties類

@ConfigurationProperties(prefix = "brx")
public class HelloProperties {

    private String weekend;

    private String name;

    public String getWeekend() {
        return weekend;
    }

    public void setWeekend(String weekend) {
        this.weekend = weekend;
    }

    
public String getName() { return name; } public void setName(String name) { this.name = name; } }

新建:將啟動類修改為一個配置類,並去除pom.xml中的maven插件

@Configuration
@EnableConfigurationProperties(HelloProperties.class)//只有在web上下文才起作用
@ConditionalOnWebApplication
public class BrxautoconfigApplication {

    @Autowired
    HelloProperties helloProperties;

    @Bean
    HelloService helloService(){
        HelloService helloService =  new HelloService();
        helloService.setHelloProperties(helloProperties);
        return helloService;
    }
}

新建:META-INF/spring.factories:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.brx.demo.brxautoconfig.BrxautoconfigApplication

3.將starter和Autocofigure項目install到本地倉庫

4.新建一個普通web項目,並添加xxxStarter庫,並在application.properties添加:

brx.weekend="周一"
brx.name="白gg"

技術分享圖片

SpringBoot編寫自定義Starter