实现自定义的spring boot starter,只需要三步:
1、一个Bean
2、一个自动配置类
3、一个META-INF/spring.factories配置文件
下面用代码演示这三步。
项目准备:
1、如果想使用Spring官网的脚手架自动生成项目代码,访问https://start.spring.io/
2、Maven依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> </dependencies>
代码演示:
1、一个Bean
@Data public class HelloService { private String msg; public String sayHello() { return "Hello " + msg; } }
另外增加了一个属性配置类
@Data @ConfigurationProperties(prefix = "hello") public class HelloServiceProperties { /** * 打招呼的内容,默认为"World!" */ private String msg = "World!"; }
2、一个自动配置类
@Configuration @EnableConfigurationProperties(value = HelloServiceProperties.class) @ConditionalOnClass(HelloService.class) @ConditionalOnProperty(prefix = "hello", value = "enable", matchIfMissing = true) public class HelloAutoConfiguration { @Autowired private HelloServiceProperties helloServiceProperties; @Bean @ConditionalOnMissingBean(HelloService.class) public HelloService helloService() { HelloService helloService = new HelloService(); helloService.setMsg(helloServiceProperties.getMsg()); return helloService; } }
3、一个META-INF/spring.factories配置文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.zyong.config.HelloAutoConfiguration
另外教一个小技巧,自动生成spring-configuration-metadata.json,这样在别的项目引用这个spring boot starter的时候,在application.properties编辑属性的时候会有提示功能,牛逼哄哄:
IntelliJ IDEA中File -> Settings -> 搜索框输入Annotation Processors -> 勾选Enable annotation processing
编译生成spring boot starter:mvn clean install
经过上面步骤,自定义的spring boot starter诞生了,接下来就可以在别的项目引用这个spring boot starter了,示例如下:
Maven依赖:
<dependency> <groupId>com.zyong</groupId> <artifactId>hello-spring-boot-starter</artifactId> <version>1.0</version> </dependency>
spring boot starter中bean的使用:
@RestController @SpringBootApplication public class HelloSpringBootStarterTestApplication { @Autowired private HelloService helloService; @RequestMapping("/") public String index() { return helloService.sayHello(); } public static void main(String[] args) { SpringApplication.run(HelloSpringBootStarterTestApplication.class, args); } }
application.properties中配置属性:
hello.msg=测试数据starter
是不是非常的简单?!YES,就是这么简单