有时,你希望在初始化 bean 之前和之后实现一些自己的逻辑。
这时,可以实现 BeanPostProcessor 接口。
这个接口目前有两个方法:

  • postProcessBeforeInitialization:在初始化方法之前调用。
  • postProcessAfterInitialization:在初始化方法之后调用。

例如:

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof User) {
            ((User) bean).setUserName("Dylan Smith");
        }
        return bean;
    }
}

如果 Spring 中有一个 User 对象,将其 userName 设置为:Dylan Smith。

实际上,我们经常使用的注解,如@Autowired、@Value、@Resource、@PostConstruct 等,都是通过 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor 实现的。

最后修改:2025 年 08 月 14 日
个人博客