本章介绍如何自定义SpringBoot的start
在使用SpringBoot的是需要使用那个模块进引入那个模块的starter就行,例如:需要使用web模块,引入spring-boot-starter-web的starter就行。要使用jdbc就引入spring-boot-starter-jdbc
1、自动装配Bean
自动装配使用配置类(@Configuration)结合Spring4 提供的条件判断注解@Conditional及Spring Boot的派生注解如@ConditionOnClass完成;
2、配置自动装配Bean
将标注@Configuration的自动配置类,放在classpath下META- INF/spring.factories文件中,如:
1 # Auto Configure 2 org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 3 org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\ 4 org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
3、自动装配顺序
在特定自动装配Class之前 @AutoConfigureBefore
在特定自动装配Class之后 @AutoConfigureAfter
指定顺序 @AutoConfigureOrder
4、启动器(starter)
启动器模块是一个空 JAR 文件,仅提供辅助性依赖管理,这些依赖可能用于自动装配或者其他类库
命名规约:
推荐使用以下命名规约
官方命名空间
– 前缀:“spring-boot-starter-”
– 模式:spring-boot-starter-模块名
– 举例:spring-boot-starter-web、spring-boot-starter-actuator、spring-boot-starter-jdbc
自定义命名空间
– 后缀:“-spring-boot-starter”
– 模式:模块-spring-boot-starter
– 举例:mybatis-spring-boot-starter
总结:
自动配置类 @Configuration //指定这个类是一个配置类 @ConditionalOnXXX //在指定条件成立的情况下自动配置类生效 @AutoConfigureAfter //指定自动配置类的顺序 @Bean //给容器中添加组件 @ConfigurationPropertie结合相关xxxProperties类来绑定相关的配置 @EnableConfigurationProperties//让xxxProperties生效加入到容器中 自动配置类要能加载 将需要启动就加载的自动配置类,配置在META‐INF/spring.factories # Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\ org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
自定义starter定义
1、在idea中新建一个空工程
2、在空工程中,新建2个模块 hello-springboot-starter 和 hello-springboot-starter-autoconfiger,2个都是maven工程
hello-springboot-starter 依赖 hello-springboot-starter-autoconfiger工程
目录结构如下:
hello-springboot-starter的pom.xml文件如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>com.test</groupId> 8 <artifactId>hello-springboot-starter</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 11 <!-- 启动器 --> 12 <dependencies> 13 14 <!-- 引入自动配置模块 --> 15 <dependency> 16 <groupId>com.test</groupId> 17 <artifactId>hello-springboot-starter-autoconfiger</artifactId> 18 <version>1.0-SNAPSHOT</version> 19 </dependency> 20 21 </dependencies> 22 23 </project>