jersey集成spring使用,资源类以下:java
@Singleton @Path("user") public class UserResource { @Context UriInfo uri; @Context HttpHeaders header; private UserService userService; //Service which will do all data retrieval/manipulation work public UserService getUserService() { return userService; } @Resource public void setUserService(UserService userService) { this.userService = userService; } }
在applicationContext.xml中配置以下:spring
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd "> <context:component-scan base-package="service,dao,entity,resource" /> <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="userService" class="service.UserServiceImpl"> </bean> <bean id="userDao" class="dao.UserDaoImpl"> </bean> <bean id="userResource" class="resource.UserResource"> </bean> ………………
结果测试时,发现报NullPointerException,后来多方查证、试验,发如今applicationContext.xml中以下配置无效,app
<bean id="userResource" class="resource.UserResource"> </bean>
而非Resource的类在applicationContext.xml配置都可成功初始化。解决方案是:测试
必须在UserResource类的声明上加@Component/@Repository/@Service/@Controller(其中一个便可),以下:this
@Singleton @Path("user") @Component //@Repository/@Service/@Controller public class UserResource { @Context UriInfo uri; @Context HttpHeaders header; private UserService userService; //Service which will do all data retrieval/manipulation work public UserService getUserService() { return userService; } @Resource public void setUserService(UserService userService) { this.userService = userService; }
至于形成这一现象的缘由,我尚不清晰,初步粗浅估计是jersey-spring对于annotation的支持的设计上不够完善。spa
有知晓缘由的,还请不吝赐教。设计