spring 的starter启动器能实现默认配置
starter的目录如下:
resources 目录中meta-INF 中的 spring.factories 是启动器的关键。
其中的内容如下:
org.springframework.boot.autoconfigure.EnableAutoConfiguration= com.alex.MyStarterAutoConfiguration
spring 在启动加载时,会读取该配置中的 EnableAutoConfiguration 下所有类并加载,如会加载com.alex.MyStarterAutoConfiguration;
该类的代码如下:
package com.alex;
import com.mysql.cj.jdbc.Driver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(MyStarterProperties.class)
@ConditionalOnClass(MyStarter.class)
public class MyStarterAutoConfiguration {
@Autowired
private MyStarterProperties myStarterProperties;
@Bean
@ConditionalOnMissingBean(MyStarter.class)
@ConditionalOnClass(Driver.class)
public MyStarter myStarter() {
return new MyStarter(myStarterProperties.getName());
}
}
xxxAutoConfiguration 被spring识别后,会将所有的 @Bean 加载进 spring 容器,如这里的MyStarter。
注意这里的 @ConditionalOnClass(Driver.class) 意思是只有当 starter 的使用方引入了 Mysql 的驱动后,才会生成 MyStarter 的 bean 。
为了避免使用方引入本 starter 时就引用了 Mysql 的驱动,在 maven 依赖中 scope 是provided。
如下:
``` ```java package com.alex; public class MyStarter { private String name; public MyStarter(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } 4.0.0 org.example mystarter 1.0-SNAPSHOT spring-boot-starter-parent org.springframework.boot 2.2.6.RELEASE org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-actuator-autoconfigure org.springframework.boot spring-boot-configuration-processor true org.springframework.boot spring-boot-starter-test test mysql mysql-connector-java provided
配置文件就不多说了:
package com.alex;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "com.alex")
public class MyStarterProperties {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
在 starter 中的默认配置放在 starter 的 .yaml 文件中。如果客户端(即starter的使用方)需要使用自定义的配置,只需在自己的 .yaml 中覆盖该配置即可。
当客户端引用了某个启动器,而想要排除掉某些 xxxAutoConfiguration 时,写法如下:
注意这里被exclude 的类只能是 spring.factories 中 org.springframework.boot.autoconfigure.EnableAutoConfiguration 配置的类,不然会报错:



