spring @EventListener 事件与监听

1、自定义Application Event

public class MyEvent extends ApplicationEvent {
	private static final long serialVersionUID = 1L;
	private String data;

	public MyEvent(Object source, String data) {
		super(source);
		this.data = data;
	}

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}
}

2、自定义监听

@Component
public class MyListener {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@EventListener // 注意此处
	public void handleDemoEvent(MyEvent event) {
		logger.info("发布的data为:{}", event.getData());
	}
}

3、测试

@RunWith(value = SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class ListenerTest implements ApplicationContextAware {
	private static Logger logger = LoggerFactory.getLogger(ListenerTest.class);

	private ApplicationContext context = null;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.context = applicationContext;
	}

	@Test
	public void listener() {
		context.publishEvent(new MyEvent(this, "测试"));
	}

}

你可能感兴趣的:(spring)