今天尝试写了个自定义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。
org.springframework.boot spring-boot-starters1.5.11.RELEASE
org.springframework.boot spring-boot-starter
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官方文档
44. Creating your own auto-configuration



