SpringBoot 的ApplicationListener接口以及自定义ApplicationEvent发布事件

ApplicationListener接口

监听容器刷新完成, 做一些初始化的操作

/**
 * 1. 定义一个自己应用的启动类监听,用于监听spring容器刷新完成,
 * 2. 可以初始化自己的应用
 */
@Component
public class MyApplicationBootStrapListenr implements ApplicationListener<ContextRefreshedEvent> {

    public void onApplicationEvent(ContextRefreshedEvent event) {
        MyApplicationBootStrap myApplicationBootStrap = new MyApplicationBootStrap();
        myApplicationBootStrap.init();
    }

}

/**
 * 定义一个自己应用的启动类
 */

class MyApplicationBootStrap {
    public void init() {
        System.out.println("-----MyApplicationBootStrap---被init了");
    }

}

在这里插入图片描述

自定义事件

在这里插入图片描述
查看ContextRefreshedEvent的类图,继承ApplicationContextEvent
都是一些对ApplicationContext的一些扩展事件。
在这里插入图片描述

再往上看,是ApplicationEvent类(Base class for events)

我们可以继承该类做一些自定义操作。
以注册用户发送优惠券为例。

  1. CreateUserEvent事件以及CreateUserListener监听器。
  2. Controller 注册用户。
  3. Service保存用户,同时发布事件。

CreateUserListener

@Component
public class CreateUserListener implements ApplicationListener<CreateUserEvent> {

    @Override
    public void onApplicationEvent(CreateUserEvent createUserEvent) {
        createUserEvent.sendCoupon();
    }
}

CreateUserEvent

public class CreateUserEvent extends ApplicationEvent {

    private String userName;

    public CreateUserEvent(Object source) {
        super(source);
    }


    /**
     * 发送优惠券
     */
    public void sendCoupon() {
        System.out.println("发送优惠券,保存到数据库");
        System.out.println("select * from user where username = ?");
        System.out.println("inser into coupon .... ");
    }


    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }


}

UserController

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/create")
    public String create() {
        userService.create();
        return "ok";
    }
}

UserService

public interface UserService {

    void create();
}

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WebApplicationContext applicationContext;

    @Override
    public void create() {
        System.out.println("insert into user xxxx");
        // 保存用户成功  发布事件
        CreateUserEvent createUserEvent = new CreateUserEvent(this);
        applicationContext.publishEvent(createUserEvent);
    }
}

浏览器输入:http://localhost:8080/user/create
查看结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值