Spring Boot + 事件(Event)發佈

本篇說明使用事件發佈與監聽寫法

1.新增Event物件,必須要繼承ApplicationEvent

package com.liongogo.event;

import org.springframework.context.ApplicationEvent;

public class LionGoGoEvent extends ApplicationEvent {
    public LionGoGoEvent(Object source) {
        super(source);
    }
}

2.建立SpringContextUtil,新增publishEvent方法

package com.liongogo.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext context = null;

    public SpringContextUtil() {
        super();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    public static <T> T getBean(String beanName, Class<T> clazz) {
        return context.getBean(beanName, clazz);
    }

    public static void publishEvent(ApplicationEvent pEvent){
        context.publishEvent(pEvent);
    }

}

3.建立事件監聽

package com.liongogo.event;

import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class LionGoGoListener{

    @EventListener
    public void onApplicationEvent(LionGoGoEvent event) {
        System.err.println("監聽事件:" + event.getSource());
    }
}

4.測試發佈事件

package com.liongogo.controller;

import com.liongogo.domain.SuperHero;
import com.liongogo.event.LionGoGoEvent;
import com.liongogo.util.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @RequestMapping("/event/publish")
    public String publishEvent() {
        LionGoGoEvent tLionGoGoEvent = new LionGoGoEvent("獅哥哥三日不寫Code,面目可憎");
        SpringContextUtil.publishEvent(tLionGoGoEvent);
        return "發佈事件成功";
    }
}