探索Spring Boot中@PostConstruct的魔法

开发 项目管理
具体实现类是InitDestroyAnnotationBeanPostProcessor,具体的逻辑是:先查询被@PostConstruct标记的方法,然后使用java反射去执行这个方法。回答完后,如果他不换一个问题的话,把Springboot的扩展点都给他盘一遍。

前言

@postContruct全限定类名是javax.annotation.PostConstruct,可以看出来其本身不是Spring定义的注解,但是Spring提供了具体的实现,所以这篇文章主要分析的是@PostConstruct在Spring项目开发中的功能特性、实现方式和基本工作原理。

功能特性

从@PostConstruct注解的注释上看,可以了解到以下内容:

1、要在依赖加载后,对象佤用前执行,并且只执行一次;

2、所有支持依赖注入的类都需要支持此方法。即使类没有请求注入任何的资源,也必须调用被@PostConstruct注解标记的方法;

3、一个类中在一个方法上使用@PostConstruct注解;

4、使用@PostConstruct注解标记的方法不能有参数,除非是拦截器,可以采用拦截器规范定义的InvocationContext对象。

5、使用@PostConstruct注解标记的方法不能有返回值,实际上如果有返回值,也不会报错,但是会忽略掉;

6、使用@PostConstruct注解标记的方法的权限,public、private、protected都可以;

7、使用@PostConstruct注解标记的方法不能被static修饰,但是final是可以的;

package javax.annotation;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
@Documented
@Retention (RUNTIME)
@Target(METHOD)
public @interface PostConstruct {
}

但是在在实际的Spring项目中Bean的生命周期里,其执行的时机是:1、Bean的实例化;2、Bean内依赖属性的注入 ;3、Bean里被@PostConstruct标记的方法;

下面在实现方式里,用一个小例子来验证一下这个过程;

实现方式

1、定义一个ExampleController类,采用setter的依赖注入的方式,注入exampleService属性,另外在定义一个myPostConstruct方法用@PostConstruct注解标记;

@RestController
@Slf4j
public class ExampleController {


    private ExampleService exampleService;


    public ExampleController() {
        log.info("----ExampleController无参数构造方法被执行");
    }
    @Autowired
    public void setExampleService(ExampleService exampleService) {
        this.exampleService = exampleService;
        log.info("----ExampleController类的setExampleService方法被调用");
    }
    @PostConstruct
    public void myPostConstruct(){
        log.info("----ExampleController类的myPostConstruct方法被调用");
    }
}

2、定义ExampleService类

@Service
@Slf4j
public class ExampleService {
    public ExampleService() {
        log.info("----ExampleService的无参数构造方法被调用");
    }
}

3、定义一个单元测试,在单元测试中启动Spring容器;

@Test
public void test4(){
    log.info("----单元测试执行开始");
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.fanfu");
    log.info("----单元测试执行完毕");
}

单元测试验证结果:

图片图片

从单元测试的执行结果来看,首先,ExampleConstroller被实例化,接着是ExampleService被实例化,然后通过setter依赖注入的方式把ExampleService对象注入到了ExampleConstroller对象中,之后才开始了被@PostConstruct注解标记的myPostConstruct方法的执行。下面就单元测试的结果分析一个@PostConstruct注解的工作原理。

工作原理

@PostConstruct的工作原理的关键问题就是:在Spring容器启动的过程,被@PostConstruct标记的方法是怎么被执行的?

在被@PostConstruct标记的方法上打上断点,待程序执行的断点的时候观察一下方法调用栈信息,这时会发现:

1、Spring容器启动过程的最后一步,即把需要提前注册的一些非懒加载的单例Bean时,如ExampleController,注意这时exampleController对象实例化完成,需要注入的exampleService的属性已经被实例化,且已经注入到exampleController对象中,在BeanPostProcessor接口的扩展方法中,被@PostConstruct标记的方法开始触发执行,入口位置在AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization。

public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
      throws BeansException {


   Object result = existingBean;
   for (BeanPostProcessor processor : getBeanPostProcessors()) {
      Object current = processor.postProcessBeforeInitialization(result, beanName);
      if (current == null) {
         return result;
      }
      result = current;
   }
   return result;
}

图片图片

那么触发被@PostConstruct注解标记的方法执行的BeanPostProcessor接口的具体是实现是哪个类呢?通过debug分析,是CommonAnnotationBeanPostProcessor类。

图片图片

2、CommonAnnotationBeanPostProcessor类继承于InitDestroyAnnotationBeanPostProcessor,实际的触发@PostConstruct标记方法执行的入口是在InitDestroyAnnotationBeanPostProcessor的postProcessBeforeInitialization()

3、InitDestroyAnnotationBeanPostProcessor的postProcessBeforeInitialization()内,逻辑相对比较简洁,先查询bean中被@PostConstruct标记的方法,然后再使用java反射来执行这个方法;

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    //查询bean中被@PostConstruct标记的方法,相关的信息封在LifecycleMetadata对象的
    LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
   try {
    //使用java反射执行被@PostConstruct标记的方法
      metadata.invokeInitMethods(bean, beanName);
   }
   catch (InvocationTargetException ex) {
      throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
   }
   catch (Throwable ex) {
      throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
   }
   return bean;
}

图片图片

总结

从以上几步的分析来看,被@PostConstruct标记的方法是怎么被执行的,这个问题回答清楚了。如果面试官问你,你了解@PostContruct注解是怎么工作的吗?你就可以这么回答他:在Bean实例化、属性注入后,被@PostConstruct标记的方法是在BeanPostProcessor的扩展方法postProcessBeforeInitialization()触发执行的,具体实现类是InitDestroyAnnotationBeanPostProcessor,具体的逻辑是:先查询被@PostConstruct标记的方法,然后使用java反射去执行这个方法。回答完后,如果他不换一个问题的话,把Springboot的扩展点都给他盘一遍。

责任编辑:武晓燕 来源: 凡夫编程
相关推荐

2023-12-05 07:48:23

SpringBoot

2023-09-22 10:12:57

2022-12-19 15:12:34

python运算符

2021-06-01 05:50:03

Spring@PostConstrLifecycle

2022-05-25 09:00:00

令牌JWT安全

2024-04-18 09:34:28

Reactor项目异步编程

2019-04-25 14:25:24

Spring Bootif elseJava

2020-06-18 08:18:35

密码加密安全

2020-03-19 10:44:19

DockerSpring Boo单层镜像

2024-04-18 08:28:06

2019-03-28 11:07:56

Spring BootRedis缓存

2022-04-27 08:55:01

Spring外部化配置

2022-04-28 08:05:05

数据库数据库交互

2018-11-19 14:29:17

Spring BootXML支持

2020-08-14 10:40:35

RestTemplatRetrofitJava

2024-02-04 00:00:00

@ValidSpring@Validated

2017-04-28 08:32:40

Spring BootDubbo Activ使用

2022-02-17 13:39:09

AOP接口方式

2023-09-27 08:14:56

2022-07-28 08:33:59

JupyterPython
点赞
收藏

51CTO技术栈公众号