December 7, 2023

How to Create Spring RESTful API without using Spring Boot

Most Spring Tutorials available online teach you how to create/secure a Rest API with Spring boot. However, sometimes there will be specific use cases where you will need to create/secure REST API without using spring boot. This tutorial aims to help you create a REST application without using Spring Boot at all.

Note: If you don’t wanna use even the Spring framework, then you can read on how to create REST API in Java without Spring.

What you’ll build

A Spring REST service which will simply accept a name as a path variable in the request and say hello with that name in the response

Spring REST API

What you’ll need

  • Spring Tool Suite 4
  • JDK 11
  • MySQL Server 8
  • Maven

Tech Stack

  • Spring 5
  • JDK 11
  • Log4j 2

Bootstrap your application

Let’s bootstrap the application by creating a maven project in STS

Project Dependencies

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.favtuts</groupId>
  <artifactId>spring-rest-jwt-demo</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>spring-rest-jwt-demo Maven Webapp</name>
  <url>http://maven.apache.org</url>
    <properties>
        <java-version>11</java-version>
        <spring.version>5.2.3.RELEASE</spring.version>
        <hibernate.version>5.4.1.Final</hibernate.version>
    </properties>
    <dependencies>
        <!-- Spring Web MVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Required for converting JSON data to Java object and vice versa -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.10.1</version>
        </dependency>
        <!-- Servlet API -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>SpringRestJwt</finalName>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>2.3.2</version>
                    <configuration>
                        <source>${java-version}</source>
                        <target>${java-version}</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.3</version>
                    <configuration>
                        <warSourceDirectory>src/main/webapp</warSourceDirectory>
                        <warName>SpringRestJwt</warName>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

Spring Configuration

SpringWebInitializer.java

WebApplicationContext can be configured using web.xml or Java-based configuration as shown below

SpringWebInitializer class extends Spring’s AbstractAnnotationConfigDispatcherServletInitializer to configure the WebApplicationContext.Ezoic

123456789101112131415161718192021packagecom.javachinna.config;importorg.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;publicclassSpringWebInitializer extendsAbstractAnnotationConfigDispatcherServletInitializer {    @Override    protectedClass[] getServletConfigClasses() {        returnnewClass[] { WebConfig.class};    }    @Override    protectedString[] getServletMappings() {        returnnewString[] { "/"};    }    @Override    protectedClass[] getRootConfigClasses() {        returnnewClass[] {};    }}

Ezoic

WebConfig.java

WebConfig class implements WebMvcConfigurer to configure the Jackson message converters

@EnableWebMvc annotation is used to enable Spring MVC support

@ComponentScan annotation is used with the @Configuration annotation to tell Spring the packages to scan for annotated components.

123456789101112131415161718192021packagecom.javachinna.config;importjava.util.List;importorg.springframework.context.annotation.ComponentScan;importorg.springframework.context.annotation.Configuration;importorg.springframework.http.converter.HttpMessageConverter;importorg.springframework.http.converter.json.MappingJackson2HttpMessageConverter;importorg.springframework.web.servlet.config.annotation.EnableWebMvc;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;@EnableWebMvc@Configuration@ComponentScan("com.javachinna")publicclassWebConfig implementsWebMvcConfigurer {    @Override    publicvoidconfigureMessageConverters(List<HttpMessageConverter<?>> converters) {        converters.add(newMappingJackson2HttpMessageConverter());    }}

Ezoic

Create REST Controller

GreetController.java

Controller class for exposing a GET REST APIEzoic

1234567891011121314151617181920packagecom.javachinna.controller;importorg.apache.log4j.Logger;importorg.springframework.ui.ModelMap;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RestController;@RestControllerpublicclassGreetController {    privateLogger logger = Logger.getLogger(GreetController.class);    @GetMapping("/greet/{name}")    publicString greet(@PathVariableString name, ModelMap model) {        String greet = "Hello!!! "+ name + " How are You?";        logger.info(greet);        returngreet;    }}

Log4J Configuration

log4j.properties

12345678910111213141516# Root logger optionlog4j.rootLogger=DEBUG, stdout, file# Redirect log messages to consolelog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n# Redirect log messages to a log filelog4j.appender.file=org.apache.log4j.RollingFileAppender#outputs to Tomcat homelog4j.appender.file.File=${catalina.home}/logs/myapp.loglog4j.appender.file.MaxFileSize=5MBlog4j.appender.file.MaxBackupIndex=10log4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Ezoic

Build Application

Run mvn clean install command to clean and build the war file

Deploy Application

Deploy the generated war file in a server like tomcat and hit the URL http://localhost:8080/SpringRestJwt/greet/Chinna

Conclusion

That’s all folks. In this article, we have developed a simple Spring REST service without using Spring Boot. Thank you for reading

Leave a Reply

Your email address will not be published. Required fields are marked *