0
点赞
收藏
分享

微信扫一扫

1 Event事件传递 解耦

我阿霆哥 2022-04-04 阅读 100

Event事件传递 解耦

1 自定义事件对象

/**
 * 用户注册的事件
 * @author : look-word
 * @date : 2022-04-04 20:52
 **/
public class UserRegisteredEvent extends ApplicationEvent {

    private String name;

    public UserRegisteredEvent(Object source,String name) {
        super(source);
        this.name=name;
    }

    public String getName() {
        return name;
    }

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

2 创建事件发布类

/**
 * 注册用户
 * @author : look-word
 * @date : 2022-04-04 20:48
 **/
@Component
public class Component1 {
    /**
     * 发布事件的对象
     */
    @Autowired
    private ApplicationContext context;
    
    public void register(){
        System.out.println("注册成功");
        // 注册成功 返回的数据
        String name="张三";
        // 发送事件
        context.publishEvent(new UserRegisteredEvent(this,name));
    }
}

3 创建事件接收类

/**
 * 发送短信
 * @author : look-word
 * @date : 2022-04-04 20:48
 **/
@Component
public class Component2 {
    @EventListener
    public void aaa(UserRegisteredEvent event){
        String name = event.getName();
        System.out.println("短信成功发送给"+name);
        System.out.println(event);
    }
}

测试

@SpringBootApplication
public class A01Application {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        ConfigurableApplicationContext context = SpringApplication.run(A01Application.class, args);
        // 发送事件
        context.getBean(Component1.class).register();
    }
举报

相关推荐

0 条评论