1.自定义event
/**
* @author fuli
*/
public class ChannelChangeEvent extends ApplicationEvent {
/**
* Create a new ApplicationEvent.
*
* @param source the object on which the event initially occurred (never {@code null})
*/
public ChannelChangeEvent(ChannelDTO source) {
super(source);
}
public ChannelDTO getChannelDTO(){
//校验
Preconditions.checkState( source != null);
return (ChannelDTO) this.source;
}
}
2.创建listener
/**
* @author fuli
*/
@Component
@EnableAsync
public class ChannelListener {
/**
*引入需要执行的service
*/
@Autowired
private ChannelBizService channelBizService;
/**
* 开启监听事件
*/
@EventListener
/**
* 开启异步执行
*/
@Async
public void change(ChannelChangeEvent event) {
ChannelDTO dto = event.getChannelDTO();
/**
*监听后 需要执行的业务代码
*/
channelBizService.putChannel(dto);
}
}
3.在业务代码中发布event
@Service
public class DemoService{
/**
*引入eventPublisher
*/
@Resource
private ApplicationEventPublisher publisher;
public void demoMethod(ChannelDTO channelDTO) {
//todo 正常业务代码
/**
*发布event
*/
publisher.publishEvent(new ChannelChangeEvent(dto));
}
}