springBoot框架提供的2种容器启动后执行的方法的接口,分别为:ApplicationRunner 接口和CommandLinneRunner接口,两个使用的方法几乎一致,都是重写run方法,只是参数不一样。以下提供ApplicationRunner的示例。
@Component @Slf4j public class TestComment implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { log.info("------------init_test_init------"); } }
注意点为需加上容器启动注解,例如:@Component。
ApplicationRunner 优先于CommandLinneRunner执行,但可以通过@Order 注解来决定执行的先后顺序
@PostConstruct注解也可以实现Bean初始化后执行的方法,但它是Java自己的注解,该注解用来修饰一个非静态的void方法,@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。
@PostConstruct public void init() {
log.info("------------init_init------");
}