• @PostConstruct注解详解


    @PostConstruct注解详解

            最近在项目中遇到一个问题,一位同事由于失误注释掉了@PostConstruct注解,导致目录树缓存失效,每次都得重新去数据库取,找到问题后,顺便记录一下知识点。

    背景

             很多人以为@PostConstruct注解是Spring提供的,其实不是!@PostConstruct注解是Java自己提供的注解。
    import javax.annotation.PostConstruct;
    
             Java中该注解的说明:@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法只会被服务器执行一次。
             通常我们会是在Spring框架中使用到@PostConstruct注解。从依赖注入的字面意思就可以知道,要将对象b注入到对象a,那么首先就必须得生成对象a和对象b,才能执行注入。所以,如果一个类A中有个成员变量b被@Autowried注解,那么@Autowired注入是发生在A的构造方法执行完之后的。如果想在生成对象时完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入,那么久无法在构造函数中实现。为此,可以使用@PostConstruct注解一个方法来完成初始化,@PostConstruct注解的方法将会在依赖注入完成后被自动调用。
    该注解的方法在整个Bean初始化中的执行顺序:

    file

    但是需要注意:子类实例化过程中会调用父类中的@PostConstruct方法!
    @Component
    public class TestRootClass {
    
    	public TestRootClass() {
    		System.out.println("Root Constructor");
    	}
    
    	@PostConstruct
    	public void sayHello() {
    		System.out.println("Hello! I am Root");
    	}
    
    }
    
    @Component
    public class TestChildClass extends TestRootClass{
    
    	public TestChildClass() {
    		System.out.println("Child Constructor");
    	}
    
    	@PostConstruct
    	public void sayBye() {
    		System.out.println("Bye! I am Child");
    	}
    
    }
    
    打印结果
    Root Constructor
    Child Constructor
    Hello! I am Root
    Bye! I am Child
    Root Constructor
    Hello! I am Root
    
  • 相关阅读:
    elementui问题汇总
    微信小程序实现微信授权登录
    微信小程序数据存储
    小程序使用第三方服务,需要中转到一个h5页面,返回到指定页面
    小程序开发,通过左上角返回到指定页面
    万恶之源-基本数据类型(list,tuple)
    基础中的基础
    mybatis_plus实现自动填充和逻辑删除
    本地端口占用解决方案
    maven定义版本以来报红解决方案
  • 原文地址:https://www.cnblogs.com/miraclewu/p/12884546.html
Copyright © 2020-2023  润新知