提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
自定义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.HelloService
5. 引用自定义spring-boot-starter
- pom依赖如下:
<dependency>
<groupId>com.kerry</groupId>
<artifactId>hello-service-spring-boot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
- 注意修改Application启动类中组件扫描的路径配置,
若未正确配置新引入的starter路径可能无法正常执行
@ComponentScan({"com.kerry.netty.study01.*","com.kerry.hello.*"})
三、总结
spring-boot自动装配原理:springboot启动类上都有一个@SpringBootApplication
注解。该注解是复合注解,包含@EnableAutoConfiguration
注解,它会引入AutoConfigurationImportSelector.class
这个类,这个类会加载jar包里META-INF/spring.factories配置文件里面的配置类。