项目启动就执行的方法:
找到的四种
https://www.cnblogs.com/zuidongfeng/p/9926471.html
https://blog.csdn.net/limingcai168/article/details/92797258
其中一种:
实现CommandLineRunner接口,实现run方法。
这里的例子同时使用了发布订阅,这么设计是因为想到这个处理不一定只在项目启动时做,这样比较灵活可复用,而且方便扩展发布新的事件或者增加新的事件订阅者:
- 先定义一个事件
public class TenantEvent extends ApplicationEvent {
private String tenantId;
private String schoolId;
public TenantEvent(Object source) {
super(source);
}
public TenantEvent(Object source,String tenantId,String schoolId) {
super(source);
this.tenantId = tenantId;
this.schoolId = schoolId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getSchoolId() {
return schoolId;
}
public void setSchoolId(String schoolId) {
this.schoolId = schoolId;
}
}
- 在run方法中发布事件
@Component
@Slf4j
@Transactional
public class InitRunner implements CommandLineRunner {
@Autowired
private ApplicationEventPublisher eventPublisher;
@Override
public void run(String... args) throws Exception {
// do something...
TenantEvent tenantEvent = new TenantEvent(tenantConfig,tenantConfig.getTenantId(), tenantConfig.getSchoolId());
eventPublisher.publishEvent(tenantEvent);
}
}
- 事件监听,处理者
@EventListener
public void initDiskRoles(TenantEvent tenantEvent) {
// do something
}
发布订阅模式的优点缺点:
https://blog.csdn.net/weixin_34415923/article/details/91385712