提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
自定义spring-boot-starter- 一、spring-boot 自动装配揭秘?
- 二、自定义spring-boot-starter
- 1.HelloServiceProperties配置映射
- 2. 自动加载配置HelloServiceAutoConfiguration
- 3. 自动装配类HelloService
- 4. spring.factories配置文件
- 5. 引用自定义spring-boot-starter
- 三、总结
一、spring-boot 自动装配揭秘?
-
复合注解 @SpringBootApplication包含以下三个注解:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan -
注解@EnableAutoConfiguration 包含注解@import(AutoConfigurationimportSelector.class)会引用执行AutoConfigurationimportSelector中selectimports()方法
@Override
public String[] selectimports(Annotationmetadata annotationmetadata) {
if (!isEnabled(annotationmetadata)) {
return NO_importS;
}
AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(annotationmetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
该方法会调用org.springframework.core.io.support.SpringFactoriesLoader#loadSpringFactories(),默认自动加载装配meta-INF/spring.factories文件中配置的类。
二、自定义spring-boot-starter **命名规则**Spring官方建议非官方Starter命名应遵循 {name}-spring-boot-starter 的格式
1.HelloServiceProperties配置映射代码如下(示例):
@ConfigurationProperties(prefix = "hello.service")
public class HelloServiceProperties {
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2. 自动加载配置HelloServiceAutoConfiguration
代码如下(示例):
@Configuration
@ConditionalOnClass(HelloService.class)
@EnableConfigurationProperties(HelloServiceProperties.class)
public class HelloServiceAutoConfiguration {
@Bean
public HelloService helloService(HelloServiceProperties properties) {
System.out.println("@Bean执行");
return new HelloService(properties.getName(), properties.getAge());
}
}
3. 自动装配类HelloService
代码如下(示例):
public class HelloService {
private String name;
private int age;
public HelloService() {
}
public HelloService(String name, int age) {
this.name = name;
this.age = age;
}
public String sayHello() {
return "hello " + name + "年龄:" + age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
4. spring.factories配置文件
代码如下(示例):
org.springframework.boot.autoconfigure.EnableAutoConfiguration= com.kerry.hello.service.HelloService5. 引用自定义spring-boot-starter
- pom依赖如下:
com.kerry hello-service-spring-boot-starter 0.0.1-SNAPSHOT
- 注意修改Application启动类中组件扫描的路径配置,
若未正确配置新引入的starter路径可能无法正常执行
@ComponentScan({"com.kerry.netty.study01.*","com.kerry.hello.*"})
三、总结 spring-boot自动装配原理:
springboot启动类上都有一个@SpringBootApplication注解。该注解是复合注解,包含@EnableAutoConfiguration注解,它会引入AutoConfigurationimportSelector.class这个类,这个类会加载jar包里meta-INF/spring.factories配置文件里面的配置类。



