Jersey REST服务作为Spring组件

5

我在我的应用程序中有一个REST服务,我希望它使用Spring Beans。 我正在使用的Spring版本是2.5。 web.xml文件的一部分:

<servlet>
    <servlet-name>jersey-servlet</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.app.rest</param-value>
    </init-param>
    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>jersey-servlet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

在pom.xml文件中,我有依赖项:
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-server</artifactId>
    <version>1.8</version>
</dependency>
<dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>1.8</version>
</dependency>

在 context.xml 文件中,我已经添加了以下内容:
<context:component-scan base-package="com.app.rest"/>

并且:
<tx:annotation-driven proxy-target-class="true" />

服务类的有趣部分:

@Component
@Path("/notification")
@Scope("singleton")
public class PushNotification {

    @Autowired
    //@Resource(name = "sendMessageServiceFacade")
    private SendMessageServiceFacade sendMessageServiceFacade;

    @Autowired
    //@Resource(name = "responseCode")
    private NotificationResponseMessage responseCode;

    @Autowired
    //@Resource(name = "validator")
    private PushMessagePreValidator validator;

    @POST
    @Path("/register")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response registerDevice(PushWooshRegisterDeviceDto dto) {
        if (validator.validate(dto) == 200) {
            return invokePushMessage(dto, PushMessageType.REGISTER.getMsgType());
        } else {
            return buildFailResponse();
        }
    }

    @GET
    @Path("/{param}")
    public Response ping(@PathParam("param") String param) {
        return Response.status(200).entity(param).build();
    }

GET方法按预期工作(基本上它能正常工作:)),但POST方法在if(validator.validate(dto)== 200)的行上抛出NullPointerException异常。

我不知道为什么@Autowired注释在这里不起作用,我试过使用@Resource-效果相同。

任何提示都可能有所帮助。

提前感谢, Marek。

2个回答

3

我希望能够在没有Jersey-Spring的情况下完成它,好吧,我将在这个依赖项中添加Spring的排除,并希望它能正常工作 :) - Marek

0
如果您实现了org.springframework.validation.Validator接口,您应该会看到validate方法期望两个参数,类型分别为ObjectErrors,因此您需要在validate调用中添加另一个类。
BeanPropertyBindingResult v = new BeanPropertyBindingResult(dto,"Errors");
validator.validate(dto, v);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接