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
有知曉緣由的,還請不吝賜教。設計