Exemple d’intégration RESTEasy Spring

Nous vous montrons ici deux manières générales d’injecter Spring Bean dans JBoss RESTEasy . Les solutions ci-dessous devraient fonctionner sur la plupart des infrastructures Web et des implémentations JAX-RS.

  1. Utilisez WebApplicationContextUtils ServletContext.

  2. Créez une classe pour implémenter intrefaces ApplicationContextAware, avec

Le motif singleton est recommandé.

Dans ce tutoriel, nous intégrons RESTEasy 2.2.1.GA à Spring 3.0.5.RELEASE .

1. Dépendances du projet

Pas beaucoup de dépendances, déclarez simplement RESTEasy et Spring core dans votre fichier Maven pom.xml .

    <repositories>
        <repository>
          <id>JBoss repository</id>
          <url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
        </repository>
    </repositories>

    <dependencies>

        <!-- JBoss RESTEasy -->
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>2.2.1.GA</version>
        </dependency>

        <!-- Spring 3 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>

        <!-- need for solution 1, if your container don't have this -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.4</version>
        </dependency>

    </dependencies>

2. Haricot de printemps

Un simple haricot Spring nommé « customerBo », vous l’injecterez ensuite dans le service RESTEasy via Spring.

package com.mkyong.customer;

public interface CustomerBo{

    String getMsg();

}
package com.mkyong.customer.impl;

import com.mkyong.customer.CustomerBo;

public class CustomerBoImpl implements CustomerBo {

    public String getMsg() {

        return "RESTEasy + Spring example";

    }

}

File: applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">

    <bean id="customerBo" class="com.mkyong.customer.impl.CustomerBoImpl">
        </bean>

</beans>

3.1 WebApplicationContextUtils ServletContext

La première solution consiste à utiliser JAX-RS @ Context pour obtenir le ServletContext et` WebApplicationContextUtils` pour obtenir le contexte d’application Spring. Avec ce contexte d’application Spring, vous pouvez accéder aux beans et les obtenir à partir du conteneur Spring.

package com.mkyong.rest;

import javax.servlet.ServletContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.mkyong.customer.CustomerBo;

@Path("/customer")
public class PrintService {

    CustomerBo customerBo;

    @GET
    @Path("/print")
    public Response printMessage(@Context ServletContext servletContext) {

       //get Spring application context
        ApplicationContext ctx =
                     WebApplicationContextUtils.getWebApplicationContext(servletContext);
        customerBo= ctx.getBean("customerBo",CustomerBo.class);

        String result = customerBo.getMsg();

        return Response.status(200).entity(result).build();

    }

}

3.2 Implémenter ApplicationContextAware

La deuxième solution consiste à créer une classe qui implémente Spring ApplicationContextAware et à la rendre singleton pour empêcher l’instanciation à partir d’autres classes.

package com.mkyong.context;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringApplicationContext implements ApplicationContextAware {

    private static ApplicationContext appContext;

   //Private constructor prevents instantiation from other classes
        private SpringApplicationContext() {}

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        appContext = applicationContext;

    }

    public static Object getBean(String beanName) {
        return appContext.getBean(beanName);
    }

}

N’oubliez pas d’enregistrer ce haricot, sinon le conteneur Spring ne sera pas au courant de cette classe.

File: applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">

    <bean class="com.mkyong.context.SpringApplicationContext"></bean>

    <bean id="customerBo" class="com.mkyong.customer.impl.CustomerBoImpl">
        </bean>

</beans>

Dans le service REST, vous pouvez utiliser la nouvelle classe singleton - «` SpringApplicationContext` », pour obtenir le bean du conteneur Spring.

package com.mkyong.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import com.mkyong.context.SpringApplicationContext;
import com.mkyong.customer.CustomerBo;

@Path("/customer")
public class PrintService {

    CustomerBo customerBo;

    @GET
    @Path("/print")
    public Response printMessage() {

        customerBo = (CustomerBo) SpringApplicationContext.getBean("customerBo");

        String result = customerBo.getMsg();

        return Response.status(200).entity(result).build();

    }

}

4. Intégrer RESTEasy avec Spring

Pour intégrer les deux dans une application Web, ajoutez Spring «` ContextLoaderListener` »dans votre web.xml .

Fichier: web.xml

<web-app id="WebApp__ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app__2__4.xsd">
    <display-name>Restful Web Application</display-name>

    <context-param>
        <param-name>resteasy.resources</param-name>
        <param-value>com.mkyong.rest.PrintService</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
                </listener-class>
    </listener>

    <listener>
        <listener-class>
                        org.springframework.web.context.ContextLoaderListener
                </listener-class>
    </listener>

    <servlet>
        <servlet-name>resteasy-servlet</servlet-name>
        <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
                </servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>resteasy-servlet</servlet-name>
        <url-pattern>/** </url-pattern>
    </servlet-mapping>

</web-app>

5. Démo

Les solutions 1 et 2 généreront le même résultat suivant:

résultat

Télécharger le code source

Téléchargez-le - lien://wp-content/uploads/2011/07/RESTEasyt-Spring-Integration-Example.zip[RESTEasyt-Spring-Integration-Example.zip](9 Ko)

Références

Grains de printemps de l’ancien code]. lien://printemps/printemps-comment-faire-dépendance-injection-dans-votre-auditeur de session/[Général

moyen d’intégrer Spring avec d’autres framework]. http://docs.jboss.org/resteasy/docs/2.2.1.GA/userguide/html/RESTEasy Spring Integration.html[Better

Contexte d’application Spring]

lien://étiquette/intégration/[intégration]lien://étiquette/jax-rs/[jax-rs]lien://tag/resteasy/[resteasy]lien://tag/printemps/[printemps]