@PostConstruct
启动前加载
- Spring通过类(标注需要容器管理的类)的构造方法创建好一个Bean
- 执行自动注入,@Autowired @Resource
- 执行@PostConstruct标注的方法
该注解被用来修饰一个非静态的void方法,被@PostConstruct修饰的方法会在加载Servlet的时候运行,并且只会被执行一次。
- 该注解是JDK自带的。
测试代码如下:
import javax.annotation.PostConstruct;
@Slf4j
@Service
public class ArticleServiceImpl {
@PostConstruct
public void init() {
log.info("@PostConstruct标注...");
}
}
ApplicationListener
服务器容器初始化完毕之后、SpringBoot启动完毕之前加载。
- 也就是当所有的Bean都已经处理完毕之后。
- Spring容器就会发布一个ContextRefreshedEvent事件,从而触发所有实现ApplicationListener的类方法得以执行。
应用监听器,我们实现ApplicationListener接口,将其放在Spring容器中,在服务器容器初始化完毕之后SpringBoot启动完毕之前,就会执行实现的方法。
主要代码如下:
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(@NotNull ContextRefreshedEvent event) {
//这里可能会存在两个容器 分别是应用容器(根容器)和Web容器 那么加载时就可能会加载两次
if (event.getApplicationContext().getParent() == null) {
//Web容器的父容器是应用容器 这里我们获取其父类来判定是不是最顶层的应用容器
log.info("ApplicationListener初始化...");
}
}
}
CommandLineRunner和ApplicationRunner
在SpringBoot启动成功之后才会执行。
- SpringBoot项目启动成功之后,就会执行所有CommandLineRunner和ApplicationRunner实现类的实现方法。
- 执行顺序可自行设置。未设置就按照加载先后顺序进行执行。
都是实现其对应的接口即可。
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("ApplicationRunner初始化...");
}
}
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.info("CommandLineRunner初始化...");
}
}