Spring 事件机制

完成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”;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值