一、定义事件
package com.base.common.event; import com.base.common.core.domain.entity.SysUser; import org.springframework.context.ApplicationEvent; public class MyCustomEvent extends ApplicationEvent { private SysUser user; public MyCustomEvent(Object source, SysUser user) { super(source); this.user = user; } public SysUser getUser() { return user; } }
二、定义事件监听
自定义异步方法写法:
package com.base.common.event; import com.base.common.core.domain.entity.SysUser; import lombok.extern.slf4j.Slf4j; import org.springframework.context.event.EventListener; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @Component @Slf4j public class MyCustomEventListener{ @EventListener @Async public void MyCustomListener(MyCustomEvent event) throws Exception { SysUser user = event.getUser(); Thread.sleep(3000); log.info("bean-listener 收到了 publisher 发布的消息: " + user.getUserName()); } }
实现ApplicationListener接口写法:
package com.base.common.event; import com.base.common.core.domain.entity.SysUser; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationListener; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @Component @Slf4j public class MyCustomEventListener implements ApplicationListener<MyCustomEvent> { @Override @Async public void onApplicationEvent(MyCustomEvent event) { SysUser user = event.getUser(); try { Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); } log.info("bean-listener 收到了 publisher 发布的消息: " + user.getUserName()); } }
三、发布事件
@Slf4j @RestController @RequestMapping("/system/user") @AllArgsConstructor public class SysUserController extends BaseController { private final ISysUserService userService; private final ApplicationContext context; @PostMapping("/send") public AjaxResult send() { String message = "发送成功"; SysUser sysUser = userService.selectUserById(1L); MyCustomEvent event = new MyCustomEvent(this, sysUser); context.publishEvent(event); return success(message); } }
标签:SysUser,springboot,springframework,监听,public,user,import,event,事件 From: https://www.cnblogs.com/fyiyy/p/18378845