You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

未配置AutowiredAnnotationBeanPostProcessor时@Autowired注解的工作原理

问题

未配置AutowiredAnnotationBeanPostProcessor实例的情况下,以下代码中的@Autowired注解为何能正常工作?我查阅了AutowiredAnnotationBeanPostProcessor的文档,但没找到该后置处理器在本示例中被隐式注册的原因。

package com.mmeqbel.springcontainer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

public class SpringContainerApplication {

    public static void main(String[] args) {
        var app = new AnnotationConfigApplicationContext(AppConfig.class);
        var car = app.getBean(Car.class);
        System.out.println(car);
    }
}

@Configuration
@PropertySource("application.properties")
class AppConfig {
    @Autowired
    Environment env;

    @Bean
    public Car car() {
        var car = new Car();
        car.setBrand(env.getProperty("car.brand"));
        return car;
    }
}

class Car {
    private String brand;

    public void setBrand(String brand) {
        this.brand = brand;
    }

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                '}';
    }
}
解答

核心原因是**AnnotationConfigApplicationContext会自动帮你注册一批核心的注解后置处理器**,其中就包含处理@Autowired的AutowiredAnnotationBeanPostProcessor,根本不需要你手动配置。

具体过程是这样的:

  • 当你用AnnotationConfigApplicationContext传入@Configuration类启动容器时,初始化阶段会先注册ConfigurationClassPostProcessor这个关键后置处理器。
  • ConfigurationClassPostProcessor的职责不仅是解析@Configuration、@ComponentScan、@Bean这些注解,还会自动触发注册一系列支持注解驱动的处理器,AutowiredAnnotationBeanPostProcessor就是其中之一——它专门负责解析@Autowired、@Value这类依赖注入注解。
  • 你的AppConfig标注了@Configuration,本身会被容器作为Bean管理,所以里面的@Autowired注解会被已经注册好的AutowiredAnnotationBeanPostProcessor识别并处理,完成Environment的注入。

说白了,AnnotationConfigApplicationContext就是为注解驱动开发设计的,默认就把这些核心的基础处理器给你配好了,不用你手动加。

内容的提问来源于stack exchange,提问作者mmeqbel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 06:02:04