已解决:Spring容器中@Autowired注入的Bean为null问题
解决Jersey 2.x与Spring 5集成时REST服务中@Autowired注入Bean为Null的问题
我之前也碰到过一模一样的场景,明明Spring容器里的Bean都正常初始化了,Jersey的REST类里@Autowired的字段却始终是Null,手动拿ApplicationContext取又没问题——你的情况完全符合这个典型的集成缺失问题。
先还原一下你的场景代码:
REST服务类
package it.learning.rest; @Component @Path("/") public class GameClientCommsRestService { @Autowired @Qualifier("CommunicationBusiness") private GameClientCommunication comm; @GET @Path("/test/check/bean") @Produces(MediaType.TEXT_PLAIN) public Response testCheckCommsBean() { StringBuilder sb = new StringBuilder(); if (comm == null) { sb.append("GameClientCommunication instance is NULL!!"); } else { sb.append("GameClientCommunication instance is NOT NULL ---> SUCCESSFULLY instantiated"); } return getRestResponse(sb.toString()); } }
被注入的业务实现类
package it.learning.business.impl; public class GameClientCommunicationBusiness implements GameClientCommunication { @Override public String processesMessage(String request, String remoteIpAddress) { // Processing input... } }
Spring XML配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="it.learning" /> <context:annotation-config /> <bean id="applicationContextProvider" class="it.learning.utils.spring.ApplicationContextProvider"> </bean> <bean id="CommunicationBusiness" class="it.learning.business.impl.GameClientCommunicationBusiness"> </bean> </beans>
问题现象
- 应用启动无任何报错,Spring日志明确显示所有注解和XML配置的Bean都已成功注册到容器
- 调用
/test/check/bean接口返回GameClientCommunication instance is NULL!! - 通过
ApplicationContext手动获取CommunicationBusinessBean可以正常使用
问题根源
你没用到new关键字实例化Bean,排除了常见的手动创建对象脱离Spring管理的情况——真正的问题是Jersey和Spring之间的集成桥接依赖缺失。
Jersey本身是独立的REST框架,默认不会自动关联Spring的Bean容器。要让Jersey的REST服务类能使用Spring的@Autowired注入,必须引入专门的集成包,实现两者的上下文打通,否则Jersey会自己实例化REST类,完全不经过Spring的依赖注入流程。
解决办法
给项目的构建路径添加以下两个关键依赖:
jersey-spring4-2.28.jar:Jersey 2.28与Spring 4+/5集成的核心包,负责将Jersey的资源类纳入Spring的管理体系spring-bridge-2.5.0.jar:辅助实现Jersey和Spring的上下文桥接,确保Jersey能正确访问Spring容器中的Bean
添加完成后重新部署应用,再次调用测试接口就能看到注入成功的提示了。
内容的提问来源于stack exchange,提问作者Pan88
相关产品推荐
相关产品推荐

