【Spring Boot】Spring Boot之五種容器啓動後進行相關應用初始化操做方法

1、方式一,使用ApplicationListener<E extends ApplicationEvent>監聽ContextRefreshedEvent事件ide

/**
 * @author zhangboqing
 * @date 2019-11-03
 */
@Component
public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private MyService myService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println(">>>>>>>>>>>>>> ApplicationListener:" + myService.sayHello());
    }
}

 

2、方式二,使用SmartInitializingSingletonspa

/**
 * @author zhangboqing
 * @date 2019-11-03
 */
@Component
public class MySmartInitializingSingleton implements SmartInitializingSingleton {
    @Autowired
    private MyService myService;

    @Override
    public void afterSingletonsInstantiated() {
        System.out.println(">>>>>>>>>>>>>> SmartInitializingSingleton:" + myService.sayHello());
    }
}

 

3、方式三,使用SmartLifecyclecode

/**
 * @author zhangboqing
 * @date 2019-11-03
 */
@Component
public class MySmartLifecycle implements SmartLifecycle {

    @Autowired
    private MyService myService;

    @Override
    public void start() {
        System.out.println(">>>>>>>>>>>>>> SmartLifecycle:" + myService.sayHello());
    }

    @Override
    public boolean isAutoStartup() {
        return true;
    }

    @Override
    public void stop(Runnable callback) {

    }

    @Override
    public void stop() {

    }

    @Override
    public boolean isRunning() {
        return false;
    }

    @Override
    public int getPhase() {
        return 0;
    }
}

 

4、方式四,使用ApplicationRunnerblog

/**
 * @author zhangboqing
 * @date 2019-11-07
 */
@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Autowired
    private MyService myService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(">>>>>>>>>>>>>> ApplicationRunner:" + myService.sayHello());
    }
}

 

5、方式五,使用CommandLineRunner事件

/**
 * @author zhangboqing
 * @date 2019-11-07
 */
@Component
public class MyCommandLineRunner implements CommandLineRunner {

    @Autowired
    private MyService myService;

    @Override
    public void run(String... args) throws Exception {
        System.out.println(">>>>>>>>>>>>>> CommandLineRunner:" + myService.sayHello());
    }
}
相關文章
相關標籤/搜索