小知识,大挑战!本文正在参与“程序员必备小知识”创作活动
1. ApplicationRunner
org.springframework.boot包中定义的接口,在使用时需要定义类实现ApplicationRunner接口,并实现接口中的run()方法。
注意,实现类要注入到Spring容器中,否则SpringBoot启动时无法自动执行该类中的run()方法。
1.1 接口定义
@FunctionalInterface
public interface ApplicationRunner {
void run(ApplicationArguments args) throws Exception;
}
1.2 接口实现类
@Component
public class AutoRunApplicationRunner implements ApplicationRunner {
private static final Logger log = LoggerFactory.getLogger(AutoRunApplicationRunner.class);
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("实现ApplicationRunner的run方法自动执行,时间:{}", new Date());
}
}
1.3 执行结果:
2. CommandLineRunner
同样是org.springframework.boot包中定义的接口,在使用时需要定义类实现ApplicationRunner接口,并实现接口中的run()方法。实现类要注入到容器中,否则SpringBoot无法自动执行该类中的run()方法。
2.1 接口定义
@FunctionalInterface
public interface CommandLineRunner {
void run(String... args) throws Exception;
}
2.2 接口实现类
@Component
public class AutoRunCommandLineRunner implements CommandLineRunner {
private static final Logger log = LoggerFactory.getLogger(AutoRunCommandLineRunner.class);
@Override
public void run(String... args) throws Exception {
log.info("实现AutoRunCommandLineRunner的run方法自动执行,时间:{},参数内容:", new Date(),args);
}
}
2.3 执行结果
3. ApplicationRunner和CommandLineRunner
3.1 区别
- 两者都正常使用时,会先执行ApplicationRunner接口的实现类中run()方法,后执行CommandLineRunner的实现类中run()方法;且ApplicationRunner实现类的run()方法没有执行完之前,是不会执行CommandLineRunner实现类的run()方法。
- 两个接口的run()方法都是有参方法,不同的是ApplicationRunner对应方法参数类型是ApplicationArguments对象,而CommandLineRunner的方法参数类型是String。
在项目启动时传入参数如下
可以得到执行的结果信息:
3.2 @Order排序
对于ApplicationRunner和CommandLineRunner并不是绝对的,我们可以使用@Order注解来指定两种实现类的执行顺序。
@Order注解是spring框架中的org.springframework.core.annotation包提供的注解,详细信息:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Documented
public @interface Order {
int value() default 2147483647;
}
我们为CommandLineRunner的实现类使用注解@Order(value = 1),ApplicationRunner的实现类使用注解@Order(value = 2),则可以得到指定的执行顺序结果
4. @PostContstruct
@PostContstruct注解是Java本身的javax.annotation包中提供的注解内容,用来修饰一个非静态的方法,并在类创建完成后执行被标注的方法。
在Spring中框架中,标注该注解的方法执行顺序在构造方法和属性注入之后,即类加载完成后执行。
4.1 注解定义
@Documented
@Retention (RUNTIME)
@Target(METHOD)
public @interface PostConstruct {
}
4.2 使用方法
如果想要实现项目启动的同时自动执行方法,则需要将定义的类交给Spring容器管理。
@Component
public class AutoRunUserAnnotation {
private static final Logger log = LoggerFactory.getLogger(AutoRunUserAnnotation.class);
@PostConstruct
public void init(){
log.info("方法使用@PostConstruct注解来自动执行,时间:{}", new Date());
}
}
4.3 执行结果
在Spring框架中,如果定义的类使用了容器类注解,Spring会在容器初识化时加载所有使用相关注解的类,在容器加载完毕后,会立即执行类中使用@PostContstruct标注的方法。
当前注解标注的方法会在容器加在完成后、项目最终启动之前执行,结果如图: