Spring Boot含RSA密钥配置的@DataJpaTest编写问题
解决@DataJpaTest中RSA密钥转换失败的问题
问题场景
我按照Spring Boot指南,使用spring-boot-starter-oauth2-resource-server搭建JWT认证,在application.yml中配置了签名用的RSA密钥:
rsa: privateKey: classpath:certs/private.pem publicKey: classpath:certs/public.pem
但编写服务层测试的@DataJpaTest时出现错误:
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [java.security.interfaces.RSAPublicKey] at app//org.springframework.boot.context.properties.bind.BindConverter.convert(BindConverter.java:118) at app//org.springframework.boot.context.properties.bind.BindConverter.convert(BindConverter.java:100) at app//org.springframework.boot.context.properties.bind.BindConverter.convert(BindConverter.java:92) at app//org.springframework.boot.context.properties.bind.Binder.bindProperty(Binder.java:459) at app//org.springframework.boot.context.properties.bind.Binder.bindObject(Binder.java:403) at app//org.springframework.boot.context.properties.bind.Binder.bind(Binder.java:343)
使用@SpringBootTest时测试可正常运行,已知转换器存在于org.springframework.security.converter.RsaKeyConverters,但不知如何在@DataJpaTest中注册。且当前测试FooTest无相关依赖,本不应需要这些转换器。
解决方案
方案一:排除OAuth2相关自动配置类
@DataJpaTest会自动加载部分配置,可能意外触发了RSA配置的绑定。直接在测试类上排除OAuth2资源服务的自动配置类:
@DataJpaTest(excludeAutoConfiguration = {OAuth2ResourceServerAutoConfiguration.class}) public class FooTest { // 测试逻辑 }
方案二:使用测试专属配置文件
在src/test/resources下创建单独的application.yml,移除RSA相关配置或设置空值,避免测试环境触发密钥绑定:
rsa: privateKey: "" publicKey: ""
方案三:手动注册RSA转换器
如果需要保留配置(虽然测试无依赖场景下不推荐),可以在测试类中手动注册转换器到上下文:
@DataJpaTest @Configuration public class FooTest { @Bean public Converter<String, RSAPublicKey> publicKeyConverter() { return RsaKeyConverters.publicKey(); } @Bean public Converter<String, RSAPrivateKey> privateKeyConverter() { return RsaKeyConverters.privateKey(); } // 测试逻辑 }
方案四:隔离OAuth2配置类
把RSA密钥的配置逻辑封装到单独类中,用条件注解限定只有在OAuth2环境下才加载:
@Configuration @ConditionalOnClass(OAuth2ResourceServerProperties.class) @ConfigurationProperties(prefix = "rsa") public class RsaKeyProperties { private RSAPrivateKey privateKey; private RSAPublicKey publicKey; // getter/setter }
这样@DataJpaTest不会加载该配置类,也就不会触发转换逻辑。
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

