1、SpringBoot自定义starter
1.1、创建一个空工程
1.2、添加两个模块
- 空Maven项目
lu-hello-spring-boot-starter
- SpringBoot项目
lu-hello-spring-boot-stater-autoconfigure
1.3、lu-hello-spring-boot-starter
在Pom中引入autoconfigure,autoconfigure项目见1.4
<dependencies>
<dependency>
<groupId>com.lu</groupId>
<artifactId>lu-hello-spring-boot-stater-autoconfigure</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
1.4、lu-hello-spring-boot-stater-autoconfigure
-
pom
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> </dependencies>
-
HelloProperties,与配置文件绑定
@ConfigurationProperties("lu.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; } }
-
HelloService,编写相关业务
/** * 默认不要放在容器中 */ public class HelloService { @Autowired HelloProperties helloProperties; public String sayHello(String userName){ return helloProperties.getPrefix() + ":"+userName+">" +helloProperties.getSuffix(); } }
-
HelloServiceAutoConfiguration,自动配置类
@Configuration @EnableConfigurationProperties(HelloProperties.class)//将HelloProperties添加进容器中 public class HelloServiceAutoConfiguration { @ConditionalOnMissingBean(HelloService.class) @Bean public HelloService helloService(){ HelloService helloService = new HelloService(); return helloService; } }
-
编写spring.factories
在类路径下resources下创建文件META-INF/spring.factories
SpringBoot启动时会加载spring.factories里的类进入容器
# Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.lu.hello.auto.HelloServiceAutoConfiguration
-
对两个模块进行打包,进Maven仓库
lifecycle -> clean -> install
1.5、测试
-
创建一个SpringBoot项目
-
引入刚刚打包在Maven仓库的依赖
<dependency> <groupId>org.lu</groupId> <artifactId>lu-hello-spring-boot-starter</artifactId> <version>1.0-SNAPSHOT</version> </dependency>
-
编写配置文件application.properties
lu.hello.prefix=你好 lu.hello.suffix=嘻嘻
-
编写Controller
@RestController public class HelloController { @Autowired HelloService helloService; @GetMapping("/sayHello") public String sayHello(){ String name = helloService.sayHello("小明"); return name; } }
-
完成测试