Spring Boot + REST Jersey Part 1


In this post we will explain in a simple way the basic configuration of Spring Boot with Jersey, this is the first in a series of posts that will be explaining more advanced topics regarding the previously mentioned technologies.

1.- Configuration:

Configuring Spring Boot is a very simple task, you just need to inherit from the spring boot base project, include the dependencies of the spring modules and configure the plugins to be used in the project.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.0.RELEASE</version>
</parent>

When we inherit from the spring boot parent project, we are inheriting all the versions defined for each component so you don’t need specify the versions in each dependency.

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jersey</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
    </dependency>
</dependencies>

As you can see, you only need specify the dependencies but not the versions, they are all specified in the spring-boot-starter-parent.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

2.- Creating a main class:

Once we have completed our maven settings the next step is to create a main class for our application, this class will be responsible for the initialisation of the container and the project; the default container for the application is Jetty but as it is indicated by the dependencies in our pom.xml file, we will be using Tomcat.

/**
 *
 */
package com.raidentrance;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author raidentrance
 *
 */
@SpringBootApplication
public class SprinBootSampleApplication  {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SprinBootSampleApplication.class, args);
    }

}

One of the most common questions at this point is “Why are we using a main method if we are creating a web application?” The answer is quite simple, the application is not going to generate a war file but a fat jar, it is known as fat jar because besides the application itself, it includes an embedded container such as a Jetty or Tomcat one. In future posts we will explain how to use this in a production environment.

3.- Writing the REST web service.

To create a REST web service with spring you just have to use the annotations from the Jersey project and mark the classes with @Component to add it to the Spring context.

/**
 *
 */
package com.raidentrance.resource;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.springframework.stereotype.Component;

/**
 * @author raidentrance
 *
 */

@Component
@Path("/users")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class UserResource {

    @GET
    public String getUsers() {
     return "{\"username\":\"raidentrance\"}";
    }
}

The following lines are intended to describe the purpose of each annotation used in the present example:

  • @Component: Used to include the class UserResource in the Spring Context.
  • @Path(“users”): Used to define an endpoint where the service is going to be accessed, it is possible to put another annotation at method level to specify more complex endpoints.
  • @Produces(MediaType.APPLICATION_JSON) / @Consumes(MediaType.APPLICATION_JSON): These annotations specify that the endpoints registered on that class will consume and produce JSON files, for this reason the method getUsers() returns a JSON formatted string, it is possible to put these annotations in a method level to modify its behaviour.

4.- Registering the service:

Once we have the service and spring boot has been configured, the missing step is to register the service in Jersey, for this you have to create a class where all the services are going to be registered.

/**
 *
 */
package com.raidentrance.config;

import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;

import com.raidentrance.resource.UserResource;

/**
 * @author raidentrance
 *
 */
@Component
public class JerseyConfig extends ResourceConfig {
    public JerseyConfig() {
         register(UserResource.class);
    }
}

This class shouldn’t be invoked from anywhere in the application, just by being registered using the @Component annotation and inheriting from ResourceConfig Spring will know which configuration to use to register the services.

5.- Executing and testing.

To test the application, the only thing we need to do is to execute  SpringBootSampleApplication class as a desktop application, or using its jar file with the command:

 java -jar target/jar-name.jar

Output:

. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.4.0.RELEASE)

2016-09-02 11:23:28.005 INFO 20231 --- [ restartedMain] c.r.SprinBootSampleApplication : Starting SprinBootSampleApplication on m-C02RV1WXG8WP.local with PID 20231 (/Users/maagapi/Documents/Github/spring-boot-example/target/classes started by maagapi in /Users/maagapi/Documents/Github/spring-boot-example)
2016-09-02 11:23:28.008 INFO 20231 --- [ restartedMain] c.r.SprinBootSampleApplication : No active profile set, falling back to default profiles: default
2016-09-02 11:23:28.064 INFO 20231 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@53294542: startup date [Fri Sep 02 11:23:28 CDT 2016]; root of context hierarchy
2016-09-02 11:23:28.646 INFO 20231 --- [ restartedMain] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2016-09-02 11:23:29.000 INFO 20231 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-09-02 11:23:29.012 INFO 20231 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service Tomcat
2016-09-02 11:23:29.013 INFO 20231 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.4
2016-09-02 11:23:29.075 INFO 20231 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2016-09-02 11:23:29.075 INFO 20231 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1013 ms
2016-09-02 11:23:29.260 INFO 20231 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-09-02 11:23:29.261 INFO 20231 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2016-09-02 11:23:29.261 INFO 20231 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'com.raidentrance.config.JerseyConfig' to [/*]
2016-09-02 11:23:29.441 INFO 20231 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2016-09-02 11:23:29.469 INFO 20231 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-09-02 11:23:29.510 INFO 20231 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-09-02 11:23:29.513 INFO 20231 --- [ restartedMain] c.r.SprinBootSampleApplication : Started SprinBootSampleApplication in 2.206 seconds (JVM running for 2.542)

To test the code you should access http://localhost:8080/users in your web browser.

In the following sections we will explain how to add logs, configure spring security, spring data, error handling and deployments to production environments.

If you want to learn more about web services we recommend the following books:

You can find the complete code for this project in the following link:

https://github.com/raidentrance/spring-boot-example

Author: Alejandro Agapito Bautista

Twitter: @raidentrance

Contact: raidentrance@gmail.com

Translated by: Oscar Camacho – melchior01

Contact: adamfirstangel@hotmail.com

Anuncios

5 Comentarios »

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión /  Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s