完成Spring事件需要简单的三步
- 创建DataEvent,继承自ApplicationEvents
- 创建DataEventPublisher类,实现ApplicationEventPublisherAware接口
- 创建DataEventListener类,实现ApplicationListener接口
DataEvent类
import lombok.Data;
@Data
public class DataEvent extends ApplicationEvent {
private String message;
public DataEvent(Object source, String message) {
super(source);
this.message = message;
}
}
创建DataEventPublisher类接口
public interface DataEventPublisher {
void publishDataSuccess();
void publishDataFailure();
}
创建Publisher实现类
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
@Component
public class DefaultDataEventPublisher implements DataEventPublisher, ApplicationEventPublisherAware {
private ApplicationEventPublisher applicationEventPublisher;
@Override
public void publishDataSuccess() {
if (applicationEventPublisher != null) {
applicationEventPublisher.publishEvent(new DataEvent(this, "Success"));
}
}
@Override
public void publishDataFailure() {
if (applicationEventPublisher != null) {
applicationEventPublisher.publishEvent(new DataEvent(this, "Failure"));
}
}
@Override
public void setApplicationEventPublisher(
ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
}
创建DataEventListener实现类
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class DataEventListener implements ApplicationListener<DataEvent> {
private final static Logger LOGGER = LoggerFactory.getLogger(DataEventListener.class);
@Override
public void onApplicationEvent(DataEvent event) {
LOGGER.info("Received event message: {}", event.getMessage());
}
}
编写测试类
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DataPublisherTest {
@Autowired
private DefaultDataEventPublisher publisher;
@Test
public void publiserTest() throws Exception {
publisher.publishDataSuccess();
}
}
将会在输出的命令行中看到信息
“Received event message: Success”;