电脑
IntelliJ IDEA 2018.3 x64
1、使用IDEA创建springboot项目
@PostConstruct jdk自带的方法1.@PostConstruct说明 被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。2.@PreDestroy说明(jdk1.8之前名为@PreConstruct) 被@PreConstruct修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreConstruct修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前。3、Constructor 、 @Autowired 、 @PostConstruct的执行顺序是Constructor >> @Autowired >> @PostConstruct;所以,可以在@PostConstruct加载的类里直接使用spring依赖。 代码如下:在实际springboot环境使用中只要添加注解加入springbean管理就会在启动中调用一次PostConstruct注解的方法。package com.example.baidu.controller; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component;import org.springframework.stereotype.Controller;import org.springframework.stereotype.Service; import javax.annotation.PostConstruct;import javax.annotation.PreDestroy; import javax.servlet.annotation.ServletSecurity;import javax.servlet.annotation.WebListener; //@ServletSecurity//@WebListener//@Configuration//@Component//@Service@Controllerpublic class PostConstructController { @PostConstruct public void init() { System.out.println( '--------------------@PostConstruct2--------------------'); } @PreDestroy public void destroy() { System.out.println( '--------------------@PreDestroy--------------------'); }}
借助与java静态语句块的特性.1、这种方式想要在服务器启动时调用仍然需要依赖spring环境(只有加入spring容器中才会初始化也就是new) package com.example.baidu.service; import org.springframework.stereotype.Component; @Componentpublic class TestBeanStatic { static { System.out.println('---------------static?-------------------'); }}
使用监听器1、其实前面两种方式都可以理解成在监听器中初始化类之后调用改类的方法。2、springboot监听器之ServletContextListener3、其它监听器一般不能实现在服务器启动时调用如3.1、springboot实现HttpSessionLisener监听器3.1、springboot实现ServletRequestListener监听器
apache-maven-3.6.0 jdk1.8