自定义事件监听与注解开发
前提条件
若要实现自定义事件监听,则要满足以下三个条件:
1. Event
2. Listener
3. 发布事件
- 自定义事件则需要实现ApplicationEvent,代码如下:
package com.weixiaoyi.event;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
/**
* @author :yuanLong Wei
* @date :Created in 2019-5-16 15:28:42
* @description:自定义事件
* @modified By:
* @version: 1.0
*/
@Slf4j
public class RestEvent extends ApplicationEvent {
/**
* Create a new ApplicationEvent.
*
* @param source the object on which the event initially occurred (never {@code null})
*/
public RestEvent(Object source) {
super(source);
log.info("RestEvent执行了。。。");
}
}
- 自定义的监听器则需要实现ApplicationListener,这里传入的泛型则是自定义的事件类型,代码如下:
package com.weixiaoyi.listener;
import com.weixiaoyi.event.RestEvent;
import com.weixiaoyi.vo.RestVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/**
* @author :yuanLong Wei
* @date :Created in 2019-5-16 15:28:21
* @description:
* @modified By:
* @version: 1.0
*/
@Component
@Slf4j
public class RestListener implements ApplicationListener<RestEvent> {
@Override
public void onApplicationEvent(RestEvent event) {
log.info("自定义 RestListener执行了。。。。 参数为:{}",source);
}
}
- service层作为业务处理层,会发布事件:
package com.weixiaoyi.service.impl;
import com.weixiaoyi.dto.SendEventDto;
import com.weixiaoyi.event.RestEvent;
import com.weixiaoyi.service.MyEventService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author :yuanLong Wei
* @date :Created in 2019/5/16 15:35
* @description:发布事件service层实现类
* @modified By:
* @version: 1.0
*/
@Service
@Slf4j
public class MyEventServiceImpl implements MyEventService {
@Resource
private ApplicationContext applicationContext;
/**
* @see com.weixiaoyi.service.MyEventService#sendEvent(String)
*
*/
@Override
public String sendEvent(String sendName) {
log.info("sendEvent 业务执行中.....");
// 封装参数实体后 发布事件
SendEventDto sendEventDto = new SendEventDto(sendName);
applicationContext.publishEvent(new RestEvent(sendEventDto));
log.info("sendEvent 业务执行完成.....");
return "sendName";
}
}
执行结果为;
- 使用注解进行开发
代码如下:
package com.weixiaoyi.listener;
import com.weixiaoyi.event.RestEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
/**
* @author :yuanLong Wei
* @date :Created in 2019-5-16 16:09:25
* @description:注解使用
* @modified By:
* @version: 1.0
*/
@Component
@Slf4j
public class SpringStartAnnoListener {
@EventListener(classes = {RestEvent.class})
public void listenAnno(RestEvent restVo) {
log.info("listenAnno excute。。。,参数为:{}", restVo.getSource());
}
}
执行效果如下:
至此,全部开发步骤已经完成了,这里采用观察者模式,上述情况为同步方式进行业务处理,想要进行异步方式进行业务处理可以在注释方法上添加@Async:
这样就不会影响主线程正常返回值。