spring应用手册-IOC(注解实现)-(21)-@PostConstruct 注解

    科技2026-09-30  11

    戴着假发的程序员出品 抖音ID:戴着假发的程序员 欢迎关注

    @PostConstruct 注解

    spring应用手册(第二部分)

    源码:

    @Documented @Retention (RUNTIME) @Target(METHOD) public @interface PostConstruct { }

    @PostConstruct和bean标签的属性init-method有同样的作用,可以标记bean生命周期回调方法的初始化方法。

    案例:

    /** * @author 戴着假发的程序员 * * @description */ @Component public class AuthorDAO implements IAutorDAO { public AuthorDAO(){ System.out.println("实例化AuthorDAO"); } @PostConstruct public void init(){ System.out.println("执行AuthorDAO的初始化方法-init"); } @Override public String get() { return "戴着假发的程序员"; } }

    当我们初始化容器时控制台输出:

    ApplicationContext ac = new AnnotationConfigApplicationContext("com. st.dk.demo4"); 实例化AuthorDAO 执行AuthorDAO的初始化方法-init
    Processed: 0.008, SQL: 9