springboot~ EventListener事件监听的使用

栏目: Java · 发布时间: 7年前

内容简介:EventListener事件触发和监听器可以对代码解耦,在一些与业务无关的,通用的操作方法,我们可以把它设计成事件监听器,像通知,消息这些模块都可以这样设计。由于@Service也是spring组件 ,所以它里面的事件处理程序也会被注入,这时直接注入业务对象即可

EventListener事件触发和监听器可以对代码解耦,在一些与业务无关的,通用的操作方法,我们可以把它设计成事件监听器,像通知,消息这些模块都可以这样设计。

事件源

@Getter
@Builder(toBuilder = true)
public class OrderEvent {
  private String msg;
}

事件处理程序

@Component
public class OrderEventListener {
  @EventListener
  public void handleOrderEvent(OrderEvent event) {
    System.out.println("我监听到了handleOrderEvent发布的message为:" + event.getMsg());
  }
}

事件触发

@Service
public class OrderService {
  @Autowired
  private ApplicationContext context;

  public void publishOrder() {
    context.publishEvent(OrderEvent.builder().msg("建立订单").build());
  }
}

直接测试事件处理程序

@RunWith(SpringRunner.class)
@SpringBootTest
public class SecurityApplicationTests implements ApplicationContextAware {
  private ApplicationContext context = null;
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.context = applicationContext;
  }
  @Test
  public void listener() {
    context.publishEvent(OrderEvent.builder().msg("测试方法").build());
  }

测试业务代码

由于@Service也是spring组件 ,所以它里面的事件处理程序也会被注入,这时直接注入业务对象即可

@Autowired
  OrderService orderService;
  @Test
  public void listenerOrder() {
    orderService.publishOrder();
  }

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Introduction to Algorithms, 3rd Edition

Introduction to Algorithms, 3rd Edition

Thomas H. Cormen、Charles E. Leiserson、Ronald L. Rivest、Clifford Stein / The MIT Press / 2009-7-31 / USD 94.00

Some books on algorithms are rigorous but incomplete; others cover masses of material but lack rigor. Introduction to Algorithms uniquely combines rigor and comprehensiveness. The book covers a broad ......一起来看看 《Introduction to Algorithms, 3rd Edition》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具