【spring】spring自带的观察者模式【转载】

前言

转载自:https://mp.weixin.qq.com/s?srcid=0415igWGyJhQOhntXUaSd56G
在这里插入图片描述

代码示例

  • 首先,观察目标类
import lombok.Getter;
import org.springframework.context.ApplicationEvent;

/**
 * @author qilong.sun
 * @version v1.0
 * @time 2021/4/16 9:33
 * @title   观察者目标类
 * @description
 */
@Getter
public class JavaStackEvent extends ApplicationEvent {

    /**
     * Create a new {@code ApplicationEvent}.
     *
     * @param source the object on which the event initially occurred or with
     *               which the event is associated (never {@code null})
     */
    public JavaStackEvent(Object source) {
        super(source);
    }
}
  • 然后,观察者类
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;

/**
 * @author qilong.sun
 * @version v1.0
 * @time 2021/4/16 9:42
 * @title   观察者类
 * @description
 */
@RequiredArgsConstructor
public class ReaderListener implements ApplicationListener<JavaStackEvent> {

    @NonNull
    private String name;

    private String article;

    @Async
    @Override
    public void onApplicationEvent(JavaStackEvent event) {
        // 更新文章
        updateArticle(event);
    }

    private void updateArticle(JavaStackEvent event) {
        this.article = (String) event.getSource();
        System.out.printf("我是读者:%s,文章已更新为:%s\n", this.name, this.article);
    }

}
  • 最后,测试配置类;也就是用户实例
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author qilong.sun
 * @version v1.0
 * @time 2021/4/16 9:53
 * @title   测试配置类
 * @description
 */
@Slf4j
@Configuration
public class ObserverConfiguration {

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext context) {
        return (args) -> {
            log.info("发布事件:什么是观察者模式?");
            context.publishEvent(new JavaStackEvent("什么是观察者模式?"));
        };
    }

    @Bean
    public ReaderListener readerListener1(){
        return new ReaderListener("小明");
    }

    @Bean
    public ReaderListener readerListener2(){
        return new ReaderListener("小张");
    }

    @Bean
    public ReaderListener readerListener3(){
        return new ReaderListener("小爱");
    }

}

测试

启动项目,控制台打印信息:
在这里插入图片描述

理解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值