1 @EventListener 作用:
对于 Spring 容器的一些事件,可以监听并且触发相应的方法;
2 @EventListener 使用:
2.1 定义事件:
import org.springframework.context.ApplicationEvent;
public class AddDataEvent extends ApplicationEvent {
public AddDataEvent(Object source) {
super(source);
}
}
2.2 定义事件处理器:
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class AddDataEventListener {
@EventListener(value =AddDataEvent.class )
public void handleAddEvent(AddDataEvent event) {
log.info("发布的data为:{} ", JSON.toJSONString(event));
}
}
2.3 发布事件:
import org.springframework.context.ApplicationContext;
@Slf4j
@RestController
@RequestMapping("test")
public class TestController {
@Resource
private ApplicationContext applicationContext;
@GetMapping("/account/test")
public String testListener(){
applicationContext.publishEvent(new TestController());
return "success";
}
}