监听spring boot事件

1、spring.factories

com.imooc.springapplication.listener.BeforeConfigFileApplicationListener

2、application.properties

name = 小马哥

3、BeforeConfigFileApplicationListener

package com.imooc.springapplication.listener;

import org.springframework.boot.context.config.ConfigFileApplicationListener;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;

public class BeforeConfigFileApplicationListener implements Ordered, SmartApplicationListener {

    @Override
    public int getOrder() {
        //优先值越大,优先级越小(表示比ConfigFileApplicationListener的优先级小1,即先让监听器发挥作用,才能保证监听到所要监听的内容)
        return ConfigFileApplicationListener.DEFAULT_ORDER + 1;

    }

    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return ApplicationEnvironmentPreparedEvent.class.isAssignableFrom(eventType)
                || ApplicationPreparedEvent.class.isAssignableFrom(eventType);
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationEnvironmentPreparedEvent) {
            ApplicationEnvironmentPreparedEvent preparedEvent = (ApplicationEnvironmentPreparedEvent)event;
            Environment environment = preparedEvent.getEnvironment();
            System.out.println("environment.getProperties(\"name\") : " + environment.getProperty("name"));
        }
        if (event instanceof ApplicationPreparedEvent) {

        }
    }
}

4、结果

environment.getProperties("name") : ���

猜你喜欢

转载自blog.csdn.net/jiuweideqixu/article/details/86136600