首页 > 解决方案 > 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 并崩溃。我曾尝试设置断点进行调试,但它在到达断点之前崩溃。也许我没有正确调试,但我不明白为什么它不起作用。任何和所有的帮助表示赞赏!

标签: javaspring

解决方案


正如评论中提到的,最好实现 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>

推荐阅读