SpringMVC 2.5整合RESTeasy时Controller依赖注入失败排查
问题分析与解决方案
你的问题核心在于RESTeasy和Spring的Bean容器没有打通——当RESTeasy处理请求时,它是自己实例化了EmployeeController对象,而不是从Spring容器中获取你已经配置好依赖的那个Bean,自然employeeService就不会被注入,导致空指针异常。
下面是具体的解决步骤:
1. 引入RESTeasy与Spring整合的依赖
如果你的项目用Maven管理,需要添加RESTeasy的Spring整合包(版本要和你当前使用的RESTeasy版本保持一致,避免兼容性问题):
<dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-spring</artifactId> <version>你的RESTeasy版本号</version> </dependency>
2. 修改web.xml,让RESTeasy感知Spring上下文
在你的web.xml中添加Spring上下文加载监听器,以及RESTeasy的Spring整合参数,让RESTeasy从Spring容器中获取Bean实例:
<!-- 配置Spring上下文加载监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:你的Spring配置文件路径(比如servlet.xml、service.xml等)</param-value> </context-param> <!-- 保留原有RESTeasy配置,新增Spring整合参数 --> <context-param> <param-name>resteasy.servlet.mapping.prefix</param-name> <param-value>/rest</param-value> </context-param> <context-param> <param-name>resteasy.use.spring.bean.factory</param-name> <param-value>true</param-value> </context-param> <servlet> <servlet-name>resteasy-servlet</servlet-name> <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class> <init-param> <param-name>javax.ws.rs.Application</param-name> <param-value>com.test.package.controller.MyApplication</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>resteasy-servlet</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping>
3. 调整MyApplication配置(可选,更简洁的方式)
如果你希望Spring自动管理所有REST资源,可以修改MyApplication,让它从Spring上下文中自动获取带有@Path注解的Bean,不用手动添加:
@ApplicationPath("/rest") public class MyApplication extends Application { @Autowired private ApplicationContext applicationContext; @Override public Set<Object> getSingletons() { Set<Object> singletons = new HashSet<>(); // 获取所有带有@Path注解的Spring Bean Map<String, Object> restBeans = applicationContext.getBeansWithAnnotation(Path.class); singletons.addAll(restBeans.values()); return singletons; } }
4. 修复代码中的小错误
注意你的EmployeeController里的set方法名写错了,Spring依赖注入依赖规范的set方法名,这个细节会直接导致注入失败:
// 原错误代码 public void serEmployeeService (EmployeeService employeeService ) { this.employeeService = employeeService ; } // 修正后 public void setEmployeeService (EmployeeService employeeService ) { this.employeeService = employeeService ; }
验证
做完以上配置后,重启项目,调用REST接口时,RESTeasy会从Spring容器中获取已经注入好依赖的EmployeeController实例,此时employeeService不再为null,空指针异常应该就能解决了。
内容的提问来源于stack exchange,提问作者Shenali Silva
相关产品推荐
相关产品推荐

