1. 程式人生 > >33 事件監聽機制測試

33 事件監聽機制測試

1 自定義ApplicationContextInitializer

package com.gp6.springboot27.initializer;

import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;

public class MyApplicationContextInitializer implements ApplicationContextInitializer
<ConfigurableApplicationContext> { @Override public void initialize(ConfigurableApplicationContext applicationContext) { System.out.println("ApplicationContextInitializer...正在初始化..." + applicationContext); } }

2 自定義ApplicationRunner

package com.gp6.springboot27.initializer;
import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; @Component public class MyApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner...正在執行...."); } }

3 自定義SpringApplicationRunListener

package com.gp6.springboot27.initializer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

public class MySpringApplicationRunListener implements SpringApplicationRunListener {

    // 必須有的構造器
    public MySpringApplicationRunListener(SpringApplication application, String[] args){

    }

    @Override
    public void starting() {
        System.out.println("SpringApplicationRunListener...開始執行...");
    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        // 作業系統名稱
        Object o = environment.getSystemProperties().get("os.name");
        System.out.println("SpringApplicationRunListener...環境準備.."+o);
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener...IOC容器準備...");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener...載入完成...");
    }

    @Override
    public void started(ConfigurableApplicationContext context) {

    }

    @Override
    public void running(ConfigurableApplicationContext context) {

    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {

    }
}

4 加入自定義配置

org.springframework.context.ApplicationContextInitializer=\
com.gp6.springboot27.initializer.MyApplicationContextInitializer

org.springframework.boot.SpringApplicationRunListener=\
com.gp6.springboot27.initializer.MySpringApplicationRunListener

5 目錄結構

目錄結構