今天尝试写了个自定义spring boot starter, 做下笔记。
介绍
spring boot可以简化项目对spring繁琐的配置,遵循约定大于配置的原则。在没有spring boot之前, 应用里面要引入spring data jpa的时候, 需要每个应用都需要引入jpa依赖包,hibernate依赖包,以及jdbc依赖包。在使用spirng boot的时候, 只需要引入spring-boot-starter-data-jpa就可以。
官方常用的spring boot starter
官方的spring boot starter的命名规制是spring-boot-starter-***
开发中常用的spring boot starters
spring-boot-starter-web,spring-boot-starter-data-jpa,spring-boot-starter-aop
自定义starter
可以编写自定义的spring boot starter, 自定义的spring boot starter命名规则是****-spring-boot-starter
编写自定义spring starter步骤
1. 创建spring boot starter项目
2. 定义AutoConfiguration
3. 配置spring.factories
4.使用方通过maven坐标引用自定义的spring boot starter.
DEMO代码
1. 项目中引入spring boot, 项目继承自spring-boot-starters, 自定一starter依赖spring-boot-starter。
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starters</artifactId> <version>1.5.11.RELEASE</version> </parent>
<dependencies> <!-- 自定义starter依赖此spring-boot-starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> </dependencies>
2. 编写业务代码
public class MyTester { public String hello(String name) { return "hello " + name; } }
3. 编写auto-configuration代码
auto-configuration是通过@Configuration类实现的,auto-configuration classes 使用@ConditionalOnClass
and @ConditionalOnMissingBean注解。
@Configuration public class MyAutoConfiguration { @Bean @ConditionalOnMissingBean public MyTester getMyTester() { MyTester myTester = new MyTester(); return myTester; } }
4. 编写spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.zxrao.MyAutoConfiguration
参考文档
spring boot官方文档