ApplicationListener接口
监听容器刷新完成, 做一些初始化的操作
/**
* 1. 定义一个自己应用的启动类监听,用于监听spring容器刷新完成,
* 2. 可以初始化自己的应用
*/
@Component
public class MyApplicationBootStrapListenr implements ApplicationListener<ContextRefreshedEvent> {
public void onApplicationEvent(ContextRefreshedEvent event) {
MyApplicationBootStrap myApplicationBootStrap = new MyApplicationBootStrap();
myApplicationBootStrap.init();
}
}
/**
* 定义一个自己应用的启动类
*/
class MyApplicationBootStrap {
public void init() {
System.out.println("-----MyApplicationBootStrap---被init了");
}
}
自定义事件
查看ContextRefreshedEvent
的类图,继承ApplicationContextEvent
都是一些对ApplicationContext的一些扩展事件。
再往上看,是ApplicationEvent
类(Base class for events)
我们可以继承该类做一些自定义操作。
以注册用户发送优惠券为例。
- CreateUserEvent事件以及CreateUserListener监听器。
- Controller 注册用户。
- Service保存用户,同时发布事件。
CreateUserListener
@Component
public class CreateUserListener implements ApplicationListener<CreateUserEvent> {
@Override
public void onApplicationEvent(CreateUserEvent createUserEvent) {
createUserEvent.sendCoupon();
}
}
CreateUserEvent
public class CreateUserEvent extends ApplicationEvent {
private String userName;
public CreateUserEvent(Object source) {
super(source);
}
/**
* 发送优惠券
*/
public void sendCoupon() {
System.out.println("发送优惠券,保存到数据库");
System.out.println("select * from user where username = ?");
System.out.println("inser into coupon .... ");
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
UserController
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/create")
public String create() {
userService.create();
return "ok";
}
}
UserService
public interface UserService {
void create();
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private WebApplicationContext applicationContext;
@Override
public void create() {
System.out.println("insert into user xxxx");
// 保存用户成功 发布事件
CreateUserEvent createUserEvent = new CreateUserEvent(this);
applicationContext.publishEvent(createUserEvent);
}
}
浏览器输入:http://localhost:8080/user/create
查看结果: