Java 开发之 @PostConstruct 和 @PreConstruct 注解

从Java EE5规范开始,Servlet增加了两个影响Servlet生命周期的注解(Annotation):@PostConstruct和@PreConstruct。

这两个注解被用来修饰一个非静态的void()方法,而且这个方法不能有抛出异常声明。

使用方式,例如:

// 方式1    
@PostConstruct                                 
public void someMethod(){
    ...
}

// 方式2
public @PostConstruct void someMethod(){        
    ...  
}

1,@PostConstruct说明

     被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行

2,@PreDestroy说明

     被@PreDestroy修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreDestroy修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前


 

下面是在SpringBoot的用法:

@Configuration
public class myConfiguration {
    @Bean
    public InitTestFileServer initTestFileServer() {
        InitTestFileServer initTestFileServer = new InitTestFileServer();
        return initTestFileServer;
    }
}
public class InitTestFileServer {
    @PostConstruct
    public void run() {
        System.out.println("进入了@PostConstrut....");
    }
}

 

在Spring中的用法:

https://blog.csdn.net/topwqp/article/details/8681497/

 


参考来源于:

https://www.cnblogs.com/qingruihappy/p/7861623.html

https://www.cnblogs.com/landiljy/p/5764515.html

https://blog.csdn.net/topwqp/article/details/8681497/

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值