目 录CONTENT

文章目录

PostConstruct注解和CommandLineRunner

在水一方
2022-03-15 / 0 评论 / 0 点赞 / 1,178 阅读 / 754 字 / 正在检测是否收录...

PostConstruct注解是java ee自带的注解,位于package javax.annotation包下在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在spring容器初始化的时候执行该方法,实际开发中这个注解也是蛮实用的

@PostConstruct注解的方法在项目启动的时候执行这个方法,也可以理解为在spring容器启动的时候执行,可作为一些数据的常规化加载,比如数据字典、将某些需要放到缓存中的数据给存到redis中等

这个注解是由Java提供的,它用来修饰一个非静态的void方法。它会在服务器加载Servlet的时候运行,并且只运行一次

The method MUST NOT be static except for the application client

spring项目中一个bean的初始化过程中,方法执行先后顺序为:
Constructor >> @Autowired >> @PostConstruct

CommandLineRunner

在使用SpringBoot构建项目时,我们通常有一些预先数据的加载,SpringBoot提供了一个简单的方式来实现–CommandLineRunner

CommandLineRunner是一个接口,我们需要时,只需实现该接口就行。如果存在多个加载的数据,可以使用@Order注解来排序

@Component
@Order(value = 1)
public class MyStartupRunner1 implements CommandLineRunner{
@Override
public void run(String... strings) throws Exception {
    System.out.println("执行预加载数据");
    }
}

0

评论区