上海网站建设300,二手房出售信息,网站服务器用哪个好,制作个网站在服务启动时#xff0c;做一些操作#xff0c;比如加载配置#xff0c;初始化数据#xff0c;请求其他服务的接口等。 有三种方法#xff1a;
第一种是实现CommandLineRunner接口 第二种是实现ApplicationRunner接口 第三种是使用注解#xff1a;PostConstruct 三者使用…在服务启动时做一些操作比如加载配置初始化数据请求其他服务的接口等。 有三种方法
第一种是实现CommandLineRunner接口 第二种是实现ApplicationRunner接口 第三种是使用注解PostConstruct 三者使用方法 先看下三种方法分别怎么实现我们的目的
CommandLineRunner CommandLineRunner执行的时间节点是在Application完成初始化工作之后。
CommandLineRunner在有多个实现的时候可以使用order注解指定执行先后顺序。、
使用方法实现CommandLineRunner接口并重写run方法run方法里写我们的初始化操作。
示例 import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; Component public class InitTest02 implements CommandLineRunner { Override public void run(String... args) throws Exception { System.out.println(CommandLineRunner); } } ApplicationRunner ApplicationRunner跟CommandLineRunner是区别是在run方法里接收的参数不同CommandLineRuner接收的参数是String… args而ApplicationRunner的run方法的参数是ApplicationArguments 。
实现ApplicationRunner接口并重写run方法run方法里写我们的初始化操作。
示例 import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; Component public class InitTest01 implements ApplicationRunner { Override public void run(ApplicationArguments args) throws Exception { System.out.println(ApplicationRunner); } } PostConstruct PostConstruct是在对象加载完之后执行。
使用PostConstruct注解再自己写的方法上方法内写初始化逻辑
示例 import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; Component public class InitTest03 { PostConstruct public void start() { System.out.println(PostConstruct); } } 三者区别 三者都可以实现项目启动前的一些初始化操作唯一不同的是初始化的时间不同。
Spring应用启动过程中肯定是要自动扫描有Component注解的类加载类并初始化对象进行自动注入。加载类时首先要执行static静态代码块中的代码之后再初始化对象时会执行构造方法。
在对象注入完成后调用带有PostConstruct注解的方法。当容器启动成功后再根据Order注解的顺序调用CommandLineRunner和ApplicationRunner接口类中的run方法。
因此加载顺序为staticconstructerPostConstructCommandLineRunner和ApplicationRunner。