在一个空Maven项目中,新增xxxx-spring-boot-starter
和xxxx-spring-boot-autoconfigure
两个模块,xxxx
是你这个starter是做什么的,模块xxxx-spring-boot-starter
主要是作依赖管理,外界使用我们自定义的starter只需要导入我们xxxx-spring-boot-starter
模块即可。自定义的xxxx-spring-boot-autoconfigure
模块,是我们编写自动注入的地方,需要引入了Spring的spring-boot-autoconfigure
模块,这个模块在创建SpringBoot项目的时候会自动引入的,也是必须引入的,通过加载META-INF文件夹下的spring.factories文件完成自动配置的功能以及开箱即用的效果。
一,创建项目
1.1 创建空项目
输入完项目名称,点击完成进入下图步骤:
1.2 创建starter模块
选择Maven不需要使用任何模板,点击完成进入下一步
输入模块名称,点击完成即可。
1.3 创建autoconfigure模块
继续点击添加模块:
这次选择,SpringBoot项目,点击下一步
输入组织名称等信息后,点击下一步
输入模块名成等信息后,点击完成。
点击ok,完成创建。
在starter模块中引入自动配置模块:
<!--启动器-->
<dependencies><!--引入自动配置模块--><dependency><groupId>com.zyh.starter</groupId><artifactId>zyh-springboot-starter-autoconfigurer</artifactId><version>0.0.1-SNAPSHOT</version></dependency><!-- 也可导入其他模块 -->
</dependencies>
在autoconfigurer模块中引入了Spring的spring-boot-starter
模块
<!--自动引入的 也是必须引入的 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId>
</dependency>
二,编写autoconfigurer模块
2.1 创建自动配置类
仿照WebMvcAutoConfiguration自动配置,简单实现:
创建 HelloProperties
类:
@ConfigurationProperties(prefix = "zyh.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;}
}
通过@ConfigurationPropertie
注解将配置文件的内容绑定到实体类,注意:只配置@ConfigurationProperties
注解,在IOC容器中是获取不到properties配置文件转化的bean。
创建 HelloServiceAutoConfiguration
类:
@Configuration
@ConditionalOnWebApplication //web应用才生效
@EnableConfigurationProperties(HelloProperties.class) // 将HelloProperties类添加到IOC容器中
public class HelloServiceAutoConfiguration {@AutowiredHelloProperties helloProperties;@Bean// 通过 @Bean的方式注入组件public HelloService helloService(){HelloService service = new HelloService(); return service;}
}
2.2 加载自动配置类
在resources文件夹下创建META-INF/spring.factories文件,文件内容如下:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\com.zyh.HelloServiceAutoConfiguration
\
代表换行,多个自动配置类可以以" , "分割。
在autoconfigurer模块的pom中必须引入了spring-boot-autoconfigure
,这里我们来解释一下,为什么自定义satrter必须要导入spring-boot-autoconfigure
的原因,springBoot的自动装配的原理,将需要启动就加载的自动配置类,在类路径下,创建META-INF/spring.factories文件通过spi的机制加载。