Skip to content
基础

一句话答案

五种作用域:singleton(默认单例)、prototype(每次新建)、request/session/application(Web 场景)。

核心要点

三类主要扩展点:

1. BeanFactoryPostProcessor(Bean 定义级别)

  • 在 Bean 实例化之前,可以修改 BeanDefinition(如修改属性值、替换占位符)
  • 典型实现:PropertySourcesPlaceholderConfigurer(解析 ${...} 占位符)

2. BeanPostProcessor(Bean 实例级别)

  • 在 Bean 初始化前后拦截,可以修改或替换 Bean 实例
  • postProcessBeforeInitialization():@PostConstruct 之前
  • postProcessAfterInitialization():init-method 之后,AOP 代理在此生成
  • 典型实现:AutowiredAnnotationBeanPostProcessor(处理 @Autowired)、AbstractAutoProxyCreator(AOP)

3. Aware 接口(注入容器资源)

  • BeanNameAware:获取 Bean 名称
  • ApplicationContextAware:获取 ApplicationContext
  • EnvironmentAware:获取 Environment

4. 生命周期回调

  • @PostConstruct / @PreDestroy
  • InitializingBean.afterPropertiesSet() / DisposableBean.destroy()

二、AOP / 事务

追问与易错

追问方向:

  • prototype 注入到 singleton 会怎样?
  • 怎么解决 singleton 中注入 prototype?
  • request 作用域怎么注入到 singleton?

易错点:

  • ❌ prototype Bean 由 Spring 管理销毁——不管理
  • ❌ Web 作用域可以随便用——需要 Web 上下文

💡 记忆锚点

五种作用域 = 五种住房模式:singleton(合租一间房,默认)、prototype(每次来都给新房间)、request(一次请求一间)、session(一个会话一间)、application(整栋楼共享一间)。注意prototype注入singleton会变成"假多例"(永远是第一次创建的那个)。