You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

独立AWT类调用Spring Boot解密服务出现空指针异常的解决方案

问题根因

你手动通过new DecryptionService()创建的实例不受Spring容器管理,@Autowired注解的注入逻辑只有Spring容器初始化的Bean才会触发,因此你手动创建的实例里decryptor属性不会被自动赋值,最终触发空指针异常。

可行解决方案


方案1:从Spring Boot上下文获取托管的DecryptionService实例(改动最小)

适合AWT程序和Spring Boot服务在同一进程内启动的场景:

  1. 在Spring Boot启动类中添加静态上下文变量,启动完成后保存上下文:
@SpringBootApplication
public class YourBootApplication {
    // 新增静态变量保存Spring上下文
    public static ApplicationContext APP_CONTEXT;

    public static void main(String[] args) {
        APP_CONTEXT = SpringApplication.run(YourBootApplication.class, args);
    }
}
  1. 把AWT类中手动new服务的逻辑替换为从上下文取Bean:
// 替换原有 DecryptionService decryptionService = new DecryptionService();
DecryptionService decryptionService = YourBootApplication.APP_CONTEXT.getBean(DecryptionService.class);

注意:需要保证调用这段代码时Spring Boot已经完成启动流程,上下文已经完成初始化


方案2:单独初始化轻量Spring上下文加载解密依赖

适合AWT程序独立于Spring Boot主服务启动的场景,不需要启动完整Spring Boot服务,只加载解密相关的Bean:

// 仅加载解密需要的配置类和服务类,初始化轻量上下文
ApplicationContext decryptContext = new AnnotationConfigApplicationContext(RsaDecryptConfiguration.class, DecryptionService.class);
DecryptionService decryptionService = decryptContext.getBean(DecryptionService.class);

其中RsaDecryptConfiguration是你IRSADecryptor实现类对应的Spring配置类,包含解密所需的密钥、参数初始化逻辑。


方案3:手动注入依赖,不依赖Spring容器

如果不想引入Spring上下文逻辑,可以少量修改DecryptionService代码,手动传入解密器实例:

  1. 给DecryptionService新增带参构造方法:
public class DecryptionService {
    private IRSADecryptor decryptor;

    // 新增构造方法,支持手动传入解密器
    public DecryptionService(IRSADecryptor decryptor) {
        this.decryptor = decryptor;
    }

    // 原有其他逻辑保持不变
}
  1. 在AWT类中先手动初始化IRSADecryptor实现类,再创建服务实例:
// 替换原有实例化逻辑,xxx为IRSADecryptor的实现类,参数根据你的解密配置传入
IRSADecryptor decryptor = new DefaultRSADecryptor(/* 传入密钥、配置等参数 */);
DecryptionService decryptionService = new DecryptionService(decryptor);

内容的提问来源于stack exchange,提问作者Jack BeNimble

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 00:24:02