Struts2 @Inject无法在Jersey Rest webservices中工作

我已经创建了一个用于测试struts2dependency injection( @Inject )的应用程序。 注射在许多领域都很好,除了泽西rest服务类,我在其中定义了webservices动作。

我正如下所示得到例外

 Sep 22, 2014 8:48:50 AM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException SEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container java.lang.NullPointerException at usermodules.services.UserModulesServices.userName(UserModulesServices.java:30) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 

任何人都可以告诉我一些解决方案

struts2.xml

           Welcome.jsp Login.jsp    

UserModulesServices.java

 import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import net.viralpatel.struts2.action.MoreServiceImpl; import com.opensymphony.xwork2.inject.Inject; @Path("/users") public class UserModulesServices { @Inject("services") public MoreServiceImpl moreServiceImpl; public MoreServiceImpl getMoreServiceImpl() { return moreServiceImpl; } public void setMoreServiceImpl(MoreServiceImpl moreServiceImpl) { this.moreServiceImpl = moreServiceImpl; } @GET @Path("/name/{i}") @Produces(MediaType.TEXT_PLAIN) public String userName(@PathParam("i") String i) { System.out.println("name::::::::" + moreServiceImpl.validate()); return "{\"name\":\"" + i + "\"}"; } } 

MoreServiceImpl.java

 package net.viralpatel.struts2.action; public class MoreServiceImpl implements MoreServices{ @Override public String validate() { return "testing"; } } 

对于这个特殊问题,您应该提供bean配置

  

注射将起作用,但它是供内部使用的,

在内部,框架使用自己的dependency injection容器,与Google Guice非常相似。

你应该考虑其他DI框架的机会。 请参阅dependency injection 。

从官方CDI插件文档 :

使用正确的@Inject

Struts 2和它的核心组件XWork使用它自己的内部dependency injection容器。 有趣的是,你可以将它命名为JSR-330的祖母,因为它是由Crazybob Lee开发的早期预发行版Google Guice – 同样是Bob Lee,与SpringSource的Rod Johnson一起领导JSR-330规范。

也就是说,你会发现@Inject注释都是com.opensymphony.xwork2.inject.Injectjavax.inject.Inject不要混淆那两个 – javax.inject.Inject是你想要与你的Struts 2 CDI插件和CDI集成一起使用的那个 ! 虽然你也可以使用Struts的内部注释,但未定义的效果可能很奇怪 – 所以检查你的导入!

然后代替com.opensymphony.xwork2.inject.Inject
使用正确的: javax.inject.Inject