Spring JWKSet空指针异常:部署App2致运行中App1实例化失败
问题描述
我在JBoss7服务器上部署了两个应用:一个SpringBoot OAuth应用(App1),以及一个使用其生成令牌的API应用(App2)。两个应用单独部署运行均正常,但当App1处于运行状态时部署App2,App1会无法实例化JWK控制器。重新部署App1可解决该问题,但每次部署App2都会导致App1出现相同错误。请问在JBoss上部署Spring OAuth应用是否需要额外配置?
错误信息
Caused by: java.lang.RuntimeException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jwkSetController': Unsatisfied dependency expressed through field 'jwkSet'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jwkSet' defined in class path resource [oauth/config/OAuth2Conf.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.nimbusds.jose.jwk.JWKSet]: Factory method 'jwkSet' threw exception; nested exception is java.lang.NullPointerException
相关代码
@Bean public JWKSet jwkSet() { RSAKey.Builder builder = new RSAKey.Builder((RSAPublicKey) keyPair().getPublic()) .keyUse(KeyUse.SIGNATURE) .algorithm(JWSAlgorithm.RS256) .keyID(JWK_KID); return new JWKSet(builder.build()); }
解决方案
这是JBoss7类加载机制引发的跨应用冲突问题,Spring OAuth应用在JBoss容器部署时,需针对类隔离和Bean生命周期做额外配置,具体解决步骤如下:
配置应用类隔离
在App1的WEB-INF目录下创建jboss-deployment-structure.xml,强制应用使用自身打包的类,避免与容器或其他应用共享类加载器:<jboss-deployment-structure> <deployment> <exclusions> <module name="com.nimbusds.jose-jwt" /> <module name="javax.ws.rs.api" /> <module name="org.jboss.resteasy.resteasy-jaxrs" /> </exclusions> <local-last value="true" /> </deployment> </jboss-deployment-structure>固定KeyPair Bean的生命周期
错误栈显示keyPair().getPublic()返回null,说明App1的密钥对Bean在App2部署时被意外销毁或重新初始化。需明确Bean作用域并确保初始化逻辑稳定:@Bean @Scope("singleton") public KeyPair keyPair() { try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); return keyPairGenerator.generateKeyPair(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("生成RSA密钥对失败", e); } }同时给
jwkSetBean添加依赖声明,保证初始化顺序:@Bean @DependsOn("keyPair") public JWKSet jwkSet() { RSAKey.Builder builder = new RSAKey.Builder((RSAPublicKey) keyPair().getPublic()) .keyUse(KeyUse.SIGNATURE) .algorithm(JWSAlgorithm.RS256) .keyID(JWK_KID); return new JWKSet(builder.build()); }调整JBoss热部署扫描规则
修改standalone.xml中的部署扫描配置,减少跨应用的类加载干扰:<subsystem xmlns="urn:jboss:domain:deployment-scanner:1.1"> <deployment-scanner path="deployments" relative-to="jboss.server.base.dir" scan-interval="5000" deployment-timeout="60" auto-deploy-zipped="true" auto-deploy-exploded="false" scan-enabled="true" /> </subsystem>验证类加载来源
部署后通过JBoss控制台查看App1的类加载器状态,确认com.nimbusds.jose-jwt等核心类是从应用自身WEB-INF/lib加载,而非容器模块。
内容的提问来源于stack exchange,提问作者IbrahimMitko
相关产品推荐
相关产品推荐

