如何加载一些启动就需要的初始化数据呢?
CommandLineRunner
spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来实现
- 定义初始化类
MyCommandLineRunner
- 实现
CommandLineRunner
接口,并实现它的run()
方法,在该方法中编写初始化逻辑 - 注册成Bean,添加
@Component
注解即可 - 示例代码如下:
package com.shxseer.watch;
import com.shxseer.watch.netty.server.NettyServer;
import com.shxseer.watch.thread.ExecutorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author yangsonglin
* @create 2018-07-09 15:34
**/
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
NettyServer nettyServer;
@Autowired
ExecutorService executorService;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
executorService.start();
nettyServer.start();
}
}
ApplicationRunner
- 定义初始化类
MyApplicationRunner
- 实现
ApplicationRunner
接口,并实现它的run()
方法,在该方法中编写初始化逻辑 - 注册成Bean,添加
@Component
注解即可 - 示例代码如下:
@Component
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
System.out.println("...init resources by implements ApplicationRunner");
}
}
@Order注解规定了CommandLineRunner实例的运行顺序。@order(value=2) value 的值从小到大依次执行。
@Component
@Order(1)
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("...init resources by implements CommandLineRunner");
}
}
@Component
@Order(2)
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
System.out.println("...init resources by implements ApplicationRunner");
}
}
spring的初始化数据:
Spring Bean初始化的InitializingBean,init-method和PostConstruct
InitializingBean接口
InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet()方法。
在spring初始化bean的时候,如果bean实现了InitializingBean接口,在对象的所有属性被初始化后之后才会调用afterPropertiesSet()方法
@Component
public class InitialingzingBeanTest implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean..");
}
}
我们可以看出spring初始化bean肯定会在 ApplicationRunner和CommandLineRunner接口调用之前。
init-method和@PostConstruct
前面就说过官方文档上不建议使用InitializingBean接口,但是我们可以在<bean>元素的init-method属性指定bean初始化之后的操作方法,或者在指定方法上加上@PostConstruct注解来制定该方法在初始化之后调用
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@PostConstruct
public void init() {
System.out.println("init...");
}
}