工程由xxx-sprig-boot-starter
和xxx-sprig-boot-starter-configure
两个模块组成;
xxx-sprig-boot-starter
模块
xxx-sprig-boot-starter-configure
模块,没有实际代码<&#63;xml version="1.0" encoding="UTF-8"&#63;>4.0.0 com.ander ander-spring-boot-starter 1.0-SNAPSHOT com.ander ander-spring-boot-starter-configure 0.0.1-SNAPSHOT
xxx
-sprig-boot-starter-configure
模块
spring-boot-starter-web
<&#63;xml version="1.0" encoding="UTF-8"&#63;>4.0.0 org.springframework.boot spring-boot-starter-parent 2.3.10.RELEASE com.ander ander-spring-boot-starter-configure 0.0.1-SNAPSHOT ander-spring-boot-starter-configure Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web
/** * Service层 * * @Author: Ander * @Date: 2021-05-04 */ public class HelloService { private HelloServiceProperties helloServiceProperties; public String helloService(String name) { return helloServiceProperties.getPrefix() + " "+ name + " " + helloServiceProperties.getSuffix(); } public HelloServiceProperties getHelloServiceProperties() { return helloServiceProperties; } public void setHelloServiceProperties(HelloServiceProperties helloServiceProperties) { this.helloServiceProperties = helloServiceProperties; } }
/** * 属性配置类 * * @Author: Ander * @Date: 2021-05-04 */ @ConfigurationProperties(prefix = "com.ander") public class HelloServiceProperties { private String prefix = "hi"; private String suffix = "hello world"; 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; } }
@EnableConfigurationProperties({HelloServiceProperties.class})
作用:让xxxProperties生效加入到容器中
/** * 自定义starter自动配置类 * * @Author: Ander * @Date: 2021-05-04 */ @Configuration @ConditionalOnWebApplication // 指定web应用才生效 @EnableConfigurationProperties({HelloServiceProperties.class}) public class HelloServiceAutoConfigure { @Autowired private HelloServiceProperties helloServiceProperties; @Bean public HelloService helloService() { HelloService helloService = new HelloService(); helloService.setHelloServiceProperties(helloServiceProperties); return helloService; } }
注意先安装xxx-spring-boot-starter-configure
,再安装xxx-spring-boot-starter
/** * starter测试控制类 * * @Author: Ander * @Date: 2021-05-05 */ @RestController public class StarterTestController { @Autowired private HelloService helloService; @GetMapping("hello") public String hello(String name) { return helloService.helloService(name); } }
server.port=8888
com.ander.prefix=HI
com.ander.suffix=HELLO WORLD
到此这篇关于使用Spring Boot自定义starter详解的文章就介绍到这了,更多相关Spring Boot自定义starter内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!