1.启动监听ApplicationListener
spring mvc 启动监听,实现ApplicationListener<ContextRefreshedEvent>接口,然后重载 onApplicationEvent(ContextRefreshedEvent arg0)方法;在spring配置文件中添加对应的bean即可!
public class startBeanPostProcessor implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent arg0) {
if (arg0.getApplicationContext().getParent() == null) {
System.out.println("加载初始化方法");
}
}
}
在spring xml配置中添加bean <bean class="com.xxx.xxxx.startBeanPostProcessor "/>或通过注解@Service注入spring中。
2.继承spring中InitializingBean类实现其中的afterPropertiesSet方法,在方法体中写相关业务即可
@Service
public class IniMQTTServer implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("加载初始化方法");
}
}
3.使用@PostConstruct注解,这个注解可以在Spring加载这个类的时候执行一次
@Component
public class Test {
public Test(){
System.out.println("我最先执行");
}
/**
*我第二个执行
*/
@Autowired
private T t;
/**
*我第三个个执行
*/
@PostConstruct
private void init(){
System.out.println("假装有代码");
}
}
4.CommandLineRunner接口,使用CommandLineRunner接口类似于Main方法启动,可以接受一个字符串数组的命令行参数,来看一下实现
@Component
public class MyCommandLineRunner implements CommandLineRunner{
@Override
public void run(String... args) throws Exception{
System.out.println("假装有代码");
}
}
4.ApplicationRunner 接口,此种方式与实现CommandLineRunner接口的区别就是他的参数是ApplicationArguments
@Order(value = 1)
@Component
public class MyApplicationRunner implements ApplicationRunner{
@Override
public void run(ApplicationArguments args) throws Exception{
//假装有代码
}
}
我们可以看到,此类相比较于第3种方式还增加一个@Order注解,这个注解其实第3种方式也是能加的。
它的作用就是控制类的加载顺序,这个顺序是从小到大的。比如说启动时先去加载Order的value等于1的类,然后去加载等于2的类。