Spring中自定义事件并监听

自定义一个事件

@Getter
public class RealAuthSuccessEvent extends ApplicationEvent {
	//事件关联对象
	private RealAuth realAuth;
	public RealAuthSuccessEvent(Object source,RealAuth realAuth) {
		super(source);
		this.realAuth = realAuth;
	}
}

自定义监听器

//对RealAuthSuccessEvent事件进行监听
@Component
public class RealAuthListener implements ApplicationListener<RealAuthSuccessEvenet>{

    /***
     * 当事件触发,执行
     */
    @Override
    public void onApplicationEvent(RealAuthSuccessEvenetevent) {
        String number= event.getPhoneNumber();
        System.out.println("发短信");
    }
}

注入ApplicationContext 调用该对象 触发事件

@Service
public class RealAuthServiceImpl implement IRealAuthService{

    @Autowired
    ApplicationContext context;
    //实名认证审核
    public void realAuth(RealAuth realAuth) {
        DemoEvent event = new DemoEvent(this,realAuth );
        //触发事件
        context.publishEvent(event);
    }
}


猜你喜欢

转载自blog.csdn.net/hangbingbihai/article/details/80889953