SpringBoot 自动装配:根据条件,自动把第三方组件 / Bean 注入到 Spring 容器,不用手动写大量 XML、不用手动 @Bean,本质是 Spring 的条件注解 + SPI 扩展机制。
核心注解@EnableAutoConfiguration
@SpringBootApplication是复合注解,里面包含了@EnableAutoConfiguration,它就是自动装配的开关。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration // ✅开启自动装配
@ComponentScan
public @interface SpringBootApplication {}
@EnableAutoConfiguration 做了两件事
1、导入AutoConfigurationImportSelector选择器(核心类)
2、这个选择器读取META‑INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件(SpringBoot2.7+,旧版本是spring.factories)
自动配置类(xxxAutoConfiguration)
自动配置类就是 Java 配置类,一般长这样:
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class}) // 类存在才生效
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@EnableConfigurationProperties({WebMvcProperties.class})
public class WebMvcAutoConfiguration {
// 内部@Bean,条件满足就注册组件到容器
}
重点:条件注解(ConditionalOnXXX)
@ConditionalOnClass:类路径存在指定类,才生效
@ConditionalOnMissingBean:容器没有这个 Bean才创建(我们自己写的 @Bean 优先级更高,可以覆盖自动装配)
@ConditionalOnProperty:配置文件有对应配置才生效
@ConditionalOnWebApplication :web 环境才生效
自动装配流程
- 启动类加上@SpringBootApplication,触发@EnableAutoConfiguration
- AutoConfigurationImportSelector读取配置文件,拿到一批自动配置类全类名
- 根据条件注解@ConditionalOnXXX过滤这些配置类
- 符合条件的配置类生效,执行内部@Bean方法,把组件注册进 Spring 容器
- 同时绑定 application 配置,给 Bean 赋值
举例:引入spring‑boot‑starter‑web
- 存在DispatcherServlet.class → WebMvcAutoConfiguration条件成立
- 自动注册视图解析器、DispatcherServlet、资源处理器等 Bean,直接 web 项目就跑起来,不用自己配置。
自动装配Demo
整体结构:两个模块
1、demo-spring-boot-starter-autoconfigure:自动配置模块,存放自动配置类
2、demo-spring-boot-starter:starter 模块,只做 pom 聚合依赖(空项目,无代码)
测试工程 demo-test:引入自定义 starter,直接使用,无需写任何 Bean。
SpringBoot 2.7+,使用新的 META‑INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports,不再使用 spring.factories。
目录结构:
demo-spring-boot-starter-autoconfigure
└ src/main
├ java/com/demo
│ ├ autoconfigure/HelloAutoConfiguration.java
│ ├ properties/HelloProperties.java
│ └ service/HelloService.java
└ resources
└ META-INF/spring
└ org.springframework.boot.autoconfigure.imports
demo-spring-boot-starter (只有pom.xml)
demo-test 测试项目
模块 1:demo-spring-boot-starter-autoconfigure(自动配置核心)
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.15</version>
<relativePath/>
</parent>
<groupId>com.demo</groupId>
<artifactId>demo-spring-boot-starter-autoconfigure</artifactId>
<version>1.0.0</version>
<dependencies>
<!-- springboot自动配置依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<!-- 配置文件注解处理器,IDE提示yml配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>
业务 Service 类:com.demo.service.HelloService.java
package com.demo.service;
public class HelloService {
private String msg;
public String sayHello() {
return "自定义starter输出:" + msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
配置属性绑定类,读取 application.yml。
com.demo.properties.HelloProperties.java
package com.demo.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "demo.hello")
public class HelloProperties {
private String msg = "默认消息";
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
自动配置类(核心)
com.demo.autoconfigure.HelloAutoConfiguration.java
package com.demo.autoconfigure;
import com.demo.properties.HelloProperties;
import com.demo.service.HelloService;
import org.springframework.boot.autoconfigure.AutoConfiguration;
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;
/**
* 自定义自动配置类
*/
@AutoConfiguration
// classpath存在HelloService才生效
@ConditionalOnClass(HelloService.class)
// 开启属性绑定,把HelloProperties注入容器
@EnableConfigurationProperties(HelloProperties.class)
public class HelloAutoConfiguration {
private final HelloProperties helloProperties;
// 注入配置属性
public HelloAutoConfiguration(HelloProperties helloProperties) {
this.helloProperties = helloProperties;
}
/**
* @ConditionalOnMissingBean:容器中没有HelloService这个Bean,才创建
* 用户自己@Bean HelloService,则此方法不会执行,实现用户覆盖自动装配
*/
@Bean
@ConditionalOnMissingBean
public HelloService helloService() {
HelloService helloService = new HelloService();
helloService.setMsg(helloProperties.getMsg());
return helloService;
}
}
注册自动配置类【关键文件】
在 resources 下新建目录:/META‑INF/spring,再新建文件:org.springframework.boot.autoconfigure.AutoConfiguration.imports
com.demo.autoconfigure.HelloAutoConfiguration
模块 2:demo‑spring‑boot‑starter(空 starter,只做依赖聚合)
无任何 Java 代码,只依赖 autoconfigure 模块。
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.gang</groupId>
<artifactId>demo-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- starter仅仅引入自动配置模块 -->
<dependency>
<groupId>com.demo</groupId>
<artifactId>demo-spring-boot-starter-autoconfigure</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</project>
测试项目 demo-test
springboot 普通 web 项目,引入自定义 starter
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.15</version>
<relativePath/>
</parent>
<groupId>org.gang</groupId>
<artifactId>demo-test</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--引入我们自己写的starter-->
<dependency>
<groupId>com.demo</groupId>
<artifactId>demo-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</project>
application.yml
demo:
hello:
msg: 来自yml配置的消息
启动类 + 测试 Controller
package com.demotest;
import com.demo.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class TestApplication {
@Autowired
private HelloService helloService;
@GetMapping("/hello")
public String hello(){
return helloService.sayHello();
}
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
测试效果
启动demo-test后,浏览器访问:http://localhost:8080/hello 输出:自定义starter输出:来自yml配置的消息

因为导入了自定义的starter,容器启动时会制动注入helloService,所以可以直接使用@Autowired注入使用。若是测试模块中自动定义了HelloService,优先会使用用户自定义的。
覆盖自动装配核心特性
核心依靠两个东西:@ConditionalOnMissingBean + DeferredImportSelector 延迟加载机制,二者缺一不可。
1)@ConditionalOnMissingBean(条件注解)
@Bean
@ConditionalOnMissingBean
public HelloService helloService(){
return new HelloService();
}
作用:IOC 容器中不存在该类型 Bean 时,才创建当前 Bean;已经存在就跳过这个 @Bean 方法。
但光有这个注解还不够,如果自动配置类比用户的配置先解析,自动装配 Bean 先注册进容器,那用户写的 Bean 反而覆盖不了。 所以需要第二个关键:延迟导入。
2)DeferredImportSelector 延迟导入特性(AutoConfigurationImportSelector 实现该接口)
时序:
先解析启动类,执行@ComponentScan,加载用户自己写的@Configuration、@Bean,把用户的 BeanDefinition 注册到 BeanFactory。
用户全部 BeanDefinition 解析完成后,才去加载所有自动配置类(XxxAutoConfiguration)。
流程:
用户的 BeanDefinition 优先注册 → 自动配置执行@ConditionalOnMissingBean检测,发现容器已有,跳过创建 → 最终使用用户自定义 Bean,实现覆盖。
注意
现在的大模型生成demo已经相当完善,差不多都能直接运行,但还是有出错可能。本次生成自动装配demo时,一开始配置类的路径给的是:META‑INF/spring/org.springframework.boot.autoconfigure.imports,案例写好后一直提示找不到helloService,开始通过添加@ComponentScan(basePackages = {“com.demotest”, “com.demo”})指定扫描HelloService包案例才正常启动。但这样只是把HelloService当成普通配置添加到容器,不是真正的自动装配。调试时通过观察org.springframework.boot.autoconfigure.AutoConfigurationImportSelector#getAutoConfigurationEntry方法发现加载的configurations并没有自定义的HelloAutoConfiguration,最终定位到配置文件名应该为:org.springframework.boot.autoconfigure.AutoConfiguration.imports。开始发现问题的时候大模型也一直没定位到该问题,后面我把正确路径发给它,它才发现前面写错了。

还有需要注意直接复制生成的特殊字符,例如‘-’等,可能由于格式或编码不一致,导致直接复制当做文件名或使用时可能出现问题。

自动装配demo地址:https://github.com/ligangs/springbootAutoconfigureDemo.git
359




被折叠的 条评论
为什么被折叠?



