SpringBoot-事件驱动开发

在事件驱动开发中,需要有三种对象

  1. 事件本身
  2. 事件发布
  3. 事件订阅

事件

public class LoginSuccessEvent implement ApplicationEvent {
	LoginSuccessEvent(String params) {
		super(params);
	}
}

事件发布

@Component
public class EventPublisher implements ApplicationEventPublisherAware {
    private ApplicationEventPublisher applicationEventPublisher;

    public void sendEvent(ApplicationEvent event) {
        applicationEventPublisher.publishEvent(event);
    }

    // 在应用启动时会自动执行该方法,对字段进行注入
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
}

事件订阅两种实现

@Service
public class PersonService implements ApplicationListener<LoginSuccessEvent> {

    public void loginUser(String username) {
        System.out.println(username);
    }

    @Override
    public void onApplicationEvent(LoginSuccessEvent event) {
        UserEntity source = (UserEntity) event.getSource();
        loginUser(source.getUsername());
    }
}

@Service
public class GoodsService {

    @EventListener
    public void sendGoods(LoginSuccessEvent loginSuccessEvent) {
        UserEntity source = (UserEntity) loginSuccessEvent.getSource();
        System.out.println(source.getUsername());
    }
}
posted @ 2023-10-19 20:43  wzpro  阅读(111)  评论(0)    收藏  举报