java - Try/Catch 循环不会触发 IllegalStateException 上的 catch 语句
问题描述
我正在编写一个 Spring Boot 应用程序,并且有一个唯一的对象,该对象保存在数据库中,并由以下 CRUD 存储库检索:
@Repository
public interface DefaultSurveyRepository extends CrudRepository <DefaultSurvey, UUID> {
public static final UUID specialId = UUID.fromString("123e4567-e89b-12d3-a456-556642440000");
default DefaultSurvey findSpecialInstance() {
return findById(specialId).orElseThrow(() -> new IllegalStateException("No Default Survey Found"));
}
}
在我的服务类构造函数中,我尝试找到对象的 specialInstance,如果失败,我会创建一个新版本。代码如下:
@Service
@Transactional
public class AdminManagement {
private final DefaultSurveyRepository repo;
@Autowired
public AdminManagement(DefaultSurveyRepository repo) {
//Check if defaultSurvey exists.
try{
repo.findSpecialInstance();
}
catch(IllegalStateException e){
repo.save(new DefaultSurvey(UUID.fromString("123e4567-e89b-12d3-a456-556642440000"), "[]"));
}
this.repo = Objects.requireNonNull(repo);
}
.
.
.
问题是如果对象不存在,它不会捕获 IllegalStateException 并崩溃。我曾尝试设置断点进行调试,但它在到达断点之前崩溃。也许我没有正确调试,但我不明白为什么它不起作用。任何和所有的帮助表示赞赏!
解决方案
正如评论中提到的,最好实现 CommandLineRunner。另一个“简单”选项是在@PostConstruct 中保留有关您的存储库的初始化详细信息:
private final DefaultSurveyRepository repo;
@Autowired
public AdminManagement(DefaultSurveyRepository repo) {
this.repo = repo;
}
@PostConstruct
private void postConstruct() {
try{
repo.findSpecialInstance();
} catch(IllegalStateException e){
repo.save(new DefaultSurvey(UUID.fromString("123e4567-e89b-12d3-a456-556642440000"), "[]"));
}
this.repo = Objects.requireNonNull(repo);
}
请记住,Java EE 注释已在 Java9 中弃用并在 Java 11 中删除,因此您必须将其添加到 Maven pom.xml:
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
推荐阅读
- javascript - 如何从 HTML 中的外部文件链接 JS
- jquery - 如何在 jquery 中获取 data-id 值
- c++ - 如何使用 std::enable_if_t 进行完美转发?
- android - 将具有较少字段的新 POJO 类映射到现有 Room 表
- discord.py - Discord python:如何获得可以访问和/或写入通道的所有角色?
- python - 将视图连接到 Django 中的我的模型
- reactjs - 将金额从按钮向下传递到“支付”组件
- docker - docker: jwilder/nginx-proxy 后面的 seafile
- java - 与高斯模糊内核的卷积有效,其他内核无效
- java - 如何比较 Java 中 switch 语句中的 int 变量?