@PostConstruct注解的使用

最近重构公司项目,看到有用到该注解,就学习一下。

        @PostContruct是spring框架的注解,在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在spring容器初始化的时候执行该方法。

        来看一下Spring官方文档对它的介绍:

    The JSR-250 @PostConstruct and @PreDestroy annotations are generally considered best 
practice for receiving lifecycle callbacks in a modern Spring application. Using these 
annotations means that your beans are not coupled to Spring-specific interfaces. For details, see Using @PostConstruct and @PreDestroy.
    If you do not want to use the JSR-250 annotations but you still want to remove 
coupling, consider init-method and destroy-method bean definition metadata.

       大概意思是,Servlet中增加了两个影响Servlet生命周期的注解,@PostConstruct和@PreDestroy,这两个注解被用来修饰一个非静态的void()方法。

      写法有如下两种方式:

    @PostConstruct
    void Atest() {
        System.out.println("Atest()");
    }
    //或者
   @PreDestroy
    void Btest() {
        System.out.println("Btest()");
    }

        另外,spring中Constructor、@Autowired、@PostConstruct的顺序

        Constructor >> @Autowired >> @PostConstruct

        JSR是什么?

        JSR是Java Specification Requests的缩写,意思是Java 规范提案。是指向JCP(Java Community Process)提出新增一个标准化技术规范的正式请求。任何人都可以提交JSR,以向Java平台增添新的API和服务。JSR已成为Java界的一个重要标准。(来自百度百科)

        下面在SpringBoot中创建两个被@Component注解的类,来看一下@PostConstruct、@Autowired和Constructor的关系。

        创建类A

@Component
public class A {

    @Autowired
    private B b;

    public A() {
        System.out.println("A() - 默认构造");
    }

    @PostConstruct
    void Atest() {
        System.out.println("Atest()");
    }
}

        创建类B

@Component
public class B {


    public B() {
        System.out.println("B() - 默认构造");
    }

    @PostConstruct
    void Btest() {
        System.out.println("Btest()");
    }
}

        创建完成之后,运行SpringBoot程序,查看控制台输出即可,输出结果如下所示:

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值