springboot 事件监听(@EventListener实现)


springboot 事件监听(@EventListener实现)

 

应用:使用注解实现事件监听

 

 

**********************

相关注解

 

@EventListener

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EventListener {
    @AliasFor("classes")
    Class[] value() default {};  //监听的类

    @AliasFor("value")
    Class[] classes() default {};

    String condition() default "";
}

 

 

**********************

示例

 

*****************

event 层

 

CustomEvent

public class CustomEvent extends ApplicationEvent {

    private String message;

    public CustomEvent(Object source,String message){
        super(source);
        this.message=message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

 

CustomEventListener

@Component
public class CustomEventListener {

    @EventListener(CustomEvent.class)
    public void onApplicationEvent(CustomEvent customEvent){
        System.out.println("监听器接受消息:"+System.currentTimeMillis());
        System.out.println("接收到的消息为:"+customEvent.getMessage());
    }
}

 

*****************

controller 层

 

HelloController

@RestController
public class HelloController {

    @Resource
    private ApplicationContext applicationContext;

    @RequestMapping("/hello")
    public String hello(){
        System.out.println("事件开始发布消息:"+System.currentTimeMillis());
        applicationContext.publishEvent(new CustomEvent(this,"你好啊"));

        return "success";
    }
}

 

 

**********************

使用测试

 

localhost:8080/hello

2020-07-05 10:20:14.512  INFO 18472 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-07-05 10:20:14.517  INFO 18472 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 5 ms
事件开始发布消息:1593915614552
监听器接受消息:1593915614553
接收到的消息为:你好啊

 

 

你可能感兴趣的:(springboot)