Java CheckFailedException会去获取message.properties的内容吗

CheckFailedException是 Java 中一个自定义异常类,通常不会自动获取message.properties文件的内容,除非在代码中显式实现了国际化消息加载。

常见的实现方式:

1. 手动加载资源文件

复制代码
public class CheckFailedException extends RuntimeException {
    public CheckFailedException(String messageKey, Locale locale) {
        super(loadMessage(messageKey, locale));
    }
    
    private static String loadMessage(String key, Locale locale) {
        ResourceBundle bundle = ResourceBundle.getBundle("message", locale);
        return bundle.getString(key);
    }
}

2. 通过框架支持(如 Spring)

  • 在 Spring 中,可以使用 MessageSource

    @Component
    public class ExceptionService {
    @Autowired
    private MessageSource messageSource;

    复制代码
      public void throwCheckFailed(String messageKey, Object[] args) {
          String message = messageSource.getMessage(
              messageKey, 
              args, 
              LocaleContextHolder.getLocale()
          );
          throw new CheckFailedException(message);
      }

    }

3. 简单实现(不推荐)

复制代码
// 直接传递消息,不自动获取properties
throw new CheckFailedException("error.user.not.found");

判断是否自动获取:

  1. 查看异常类定义 :检查 CheckFailedException的构造函数

  2. 查看项目配置:检查是否有相关的国际化配置

  3. 查看框架集成:是否使用了 Spring、Quarkus 等框架的消息机制

建议做法:

复制代码
// 推荐:在业务层处理消息,异常只负责携带
public class BusinessService {
    @Autowired
    private MessageSource messageSource;
    
    public void checkSomething() {
        if (conditionFailed) {
            String errorMsg = messageSource.getMessage(
                "check.failed.error", 
                null, 
                Locale.getDefault()
            );
            throw new CheckFailedException(errorMsg);
        }
    }
}

总结 :标准的 CheckFailedException不会自动获取 message.properties,除非你的项目特别实现了这个功能。通常需要在抛出异常前先获取消息文本。

相关推荐
炸膛坦客2 小时前
单片机/C/C++八股:(十九)栈和堆的区别?
c语言·开发语言·c++
零雲2 小时前
java面试:了解抽象类与接口么?讲一讲它们的区别
java·开发语言·面试
Jay_Franklin3 小时前
Quarto与Python集成使用
开发语言·python·markdown
2401_831824963 小时前
代码性能剖析工具
开发语言·c++·算法
是wzoi的一名用户啊~3 小时前
【C++小游戏】2048
开发语言·c++
Sunshine for you4 小时前
C++中的职责链模式实战
开发语言·c++·算法
@我漫长的孤独流浪4 小时前
Python编程核心知识点速览
开发语言·数据库·python
qq_416018724 小时前
C++中的状态模式
开发语言·c++·算法
2401_884563244 小时前
模板代码生成工具
开发语言·c++·算法
code 小楊4 小时前
yrb 1.5.0 正式发布:Python 极简国内下载加速与全景可视化终端体验!
开发语言·python