springboot使用ApplicationListener实现观察者模式

观察者模式:当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。例如用户注册时,好几个模块可以接收到事件,并进行各自逻辑处理。

观察者模式:https://www.runoob.com/design-pattern/observer-pattern.html

跨系统可以用消息中间件进行事件通知,本系统可以用ApplicationListener进行事件通知。

观察者模式适用范围很小,要避免刻意使用设计模式导致代码由简单变复杂。

1、监听springboot启动事件

package com.example.listener;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class TestApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("contextRefreshedEvent = " + contextRefreshedEvent);
    }
}

spring还有其他许多类似event提供使用,百度。

springboot启动时会打印:

2021-07-22 14:24:33.216  INFO 7336 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
contextRefreshedEvent = org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@bcec361, started on Thu Jul 22 14:24:32 CST 2021]
2021-07-22 14:24:33.224  INFO 7336 --- [           main] com.example.SpringbootdemoApplication    : Started SpringbootdemoApplication in 1.323 seconds (JVM running for 2.017)

2、自定义观察者

定义一个事件,事件是观察者模式的核心。后续有一个推送者推送事件,一个或多个监听者监听事件。

package com.example.listener;

import org.springframework.context.ApplicationEvent;

public class NameEvent extends ApplicationEvent {
    public NameEvent(Object source) {
        super(source);
    }

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "NameEvent{" +
                "name='" + name + '\'' +
                ", source=" + source +
                '}';
    }
}

推送者:

package com.example.controller;

import com.example.listener.NameEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Controller
public class HelloController {
    //注入就可用
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @RequestMapping("/hello")
    @ResponseBody
    public String hello(Map map){
        NameEvent nameEvent = new NameEvent("1");
        nameEvent.setName("aaaa");
        applicationEventPublisher.publishEvent(nameEvent);
        return "hello1111111132323111";
    }
}

监听者1:

package com.example.listener;

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class NameListener implements ApplicationListener<NameEvent> {
    @Override
    public void onApplicationEvent(NameEvent nameEvent) {
        System.out.println("nameEvent = " + nameEvent);
    }
}

监听者2:

package com.example.listener;

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class NameListener2 implements ApplicationListener<NameEvent> {

    @Override
    public void onApplicationEvent(NameEvent nameEvent) {
        System.out.println("nameEvent2 = " + nameEvent);
    }
}

访问http://localhost:8080/hello时日志打印:

nameEvent = NameEvent{name='aaaa', source=1}
nameEvent2 = NameEvent{name='aaaa', source=1}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中,观察者模式被广泛应用于事件驱动的编程模型。Spring Boot通过使用事件和监听器来实现观察者模式,以实现对象之间的解耦和通信。 在Spring Boot中,事件是一个特殊的对象,它封装了与应用程序相关的状态信息。当某个特定的事件发生时,Spring Boot会自动通知所有注册的监听器,并将事件对象传递给它们。监听器可以根据事件的类型和内容来执行相应的操作。 下面是一个简单的示例,演示了如何在Spring Boot中使用观察者模式: 1. 创建一个事件类,例如`MyEvent`,用于封装事件的相关信息。 2. 创建一个监听器类,例如`MyEventListener`,实现`ApplicationListener`接口,并指定要监听的事件类型。 ```java import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; @Component public class MyEventListener implements ApplicationListener<MyEvent> { @Override public void onApplicationEvent(MyEvent event) { // 处理事件 System.out.println("Received event: " + event.getMessage()); } } ``` 3. 在需要触发事件的地方,使用`ApplicationEventPublisher`接口的实现类来发布事件。 ```java import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Component; @Component public class MyEventPublisher { private final ApplicationEventPublisher eventPublisher; public MyEventPublisher(ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } public void publishEvent(String message) { // 创建事件对象 MyEvent event = new MyEvent(message); // 发布事件 eventPublisher.publishEvent(event); } } ``` 通过以上步骤,我们就可以在Spring Boot中使用观察者模式了。当`MyEventPublisher`发布事件时,`MyEventListener`会自动接收到事件并执行相应的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值