SpringBoot中的Bean初始化方法——@PostConstruct

注解说明

  • 使用注解: @PostConstruct
  • 效果:在Bean初始化之后(构造方法和@Autowired之后)执行指定操作。经常用在将构造方法中的动作延迟。
  • 备注:Bean初始化时候的执行顺序: 构造方法 -> @Autowired -> @PostConstruct

代码示例

注解示例

@Component
public class PostConstructTest1 {

    @Autowired
    PostConstructTest2 postConstructTest2;

    public PostConstructTest1() {
//        postConstructTest2.hello();
    }
    @PostConstruct
    public void init() {
        // some init function
    }
}

在Bean的初始化操作中,有时候会遇到调用其他Bean的时候报空指针错误。这时候就可以将调用另一个Bean的方法这个操作放到@PostConstruct注解的方法中,将其延迟执行。

错误示例:

    @Component
    public class PostConstructTest1 {

        @Autowired
        PostConstructTest2 postConstructTest2;

        public PostConstructTest1() {
            postConstructTest2.hello();
        }
    }
    @Component
    public class PostConstructTest2 {

        public void hello() {
            System.out.println("hello, i am PostConstructTest2");
        }
    }

SpringBoot中的Bean初始化方法——@PostConstruct_第1张图片

正确示例

    @Component
    public class PostConstructTest1 {

        @Autowired
        PostConstructTest2 postConstructTest2;

        public PostConstructTest1() {
            postConstructTest2.hello();
        }
    }
@Component
public class PostConstructTest1 {

    @Autowired
    PostConstructTest2 postConstructTest2;

    public PostConstructTest1() {
//        postConstructTest2.hello();
    }
    @PostConstruct
    public void init() {
        postConstructTest2.hello();
    }
}

SpringBoot中的Bean初始化方法——@PostConstruct_第2张图片
作者个人博客原文

你可能感兴趣的:(spring,SpringBoot,java,日常小笔记)