spring

Spring Framework Components Tutorial

This is an in-depth article related to the Spring framework components.

1. Introduction

Spring Framework helps in creating stand-alone and production-ready applications. Spring Framework features are Spring MVC, JPA, Spring Boot, Micro Containers, and Messaging. It is an open-source software framework used by developers for creating web applications and services. Developers use Java technology stack for creating web apps.

spring framework components
Spring Framework

2. Spring Framework Components

2.1 Prerequisites

Java 7 or 8 is required on the linux, windows or mac operating system. Maven 3.6.1 is required for building the spring and hibernate application.

2.2 Download

You can download Java 8 can be downloaded from the Oracle web site . Apache Maven 3.6.1 can be downloaded from Apache site. Spring framework latest releases are available from the spring website.

2.3 Setup

You can set the environment variables for JAVA_HOME and PATH. They can be set as shown below:

Setup

JAVA_HOME="/desktop/jdk1.8.0_73"
export JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH
export PATH

The environment variables for maven are set as below:

Maven Environment

JAVA_HOME=”/jboss/jdk1.8.0_73″
export M2_HOME=/users/bhagvan.kommadi/Desktop/apache-maven-3.6.1
export M2=$M2_HOME/bin
export PATH=$M2:$PATH

2.4 Features of the Spring Framework 

Spring framework has features related to predefined templates, unit testing, abstraction, declarative support, modularization, exception handling, and transaction management. Programmers can use Plain Java Objects for developing web and enterprise applications. Spring applications are based on a modular architecture. Spring applications can integrate with different logging, Object, relationship mapping frameworks, scheduling frameworks, and view frameworks. It is a lightweight framework as it uses Plain Java Objects. Spring framework is referred to as framework of frameworks. It has declarative support and support for functional programming.

2.5 Evolution of Spring Framework

Spring framework was created by Rod Johnson in June 2002. The first release was done in March 2004. Spring 2.0 came out in October 2006. Spring 3.0 was released in December 2009. 4.0 version had Java 8 support and was released in December 2013. In June 2017, Spring 5.0 version was released. The current version is 5.3.

spring framework components evolution
Spring Evolution

2.6 Spring Framework Modules

spring framework components modules
Spring Framework Modules

Spring Framework has Core, Bean, Inversion of Control (IOC), and Dependency Injection Modules. Core Module has the following components:

  • Beans (Bean Factory)
  • Context
  • Expression Language (SpEL)
  • IOC and DI

Spring has modules for data access and integration features. They are :

  • Java Database Connectivity (JDBC)
  • Object Relationship Mapping (ORM)
  • Object XML Mappers (OXM)
  • Java Messaging Service (JMS)
  • Transaction (JTA)

Spring has Web modules which are :

  • Web
  • Web-Servlet
  • Web-Socket
  • Web-Portlet

The other modules of Spring Framework are :

  • Aspect-Oriented Programming (AOP)
  • Instrumentation
  • Testing (TestNG/JUnit)
  • Spring MVC (Model-View-Controller)

2.7 How to download and install Spring framework

Spring framework’s latest releases are available from the spring website. You can select the framework based on your operating system. After downloading the zip file can be extracted to a folder. The libraries in the libs folder are set in the CLASSPATH variable.

2.8 Building the Application

2.8.1 Spring

You can start building Spring applications using Spring Boot. Spring Boot has minimal configuration of Spring. Spring Boot has simplified security, tracing, application health management and runtime support for webservers. Spring configuration is done through maven pom.xml. The xml configuration is shown as below:

Spring Configuration

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>org.springframework</groupId>
    <artifactId>spring-helloworld</artifactId>
    <version>0.1.0</version>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
    </parent>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
 
    <properties>
        <java.version>1.8</java.version>
    </properties>
 
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>

You can create a HelloWorldController class as the web controller. The class is annotated using @RestController. Rest Controller is used to handle requests in Spring Model View Controller framework. Annotation @RequestMapping is used to annotate the index() method. The code for the HelloWorldController class is shown below:

HelloWorldController

package helloworld;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
 
@RestController
public class HelloWorldController {
     
    @RequestMapping("/")
    public String index() {
        return "Hello World\n";
    }
     
}

HelloWorldApp is created as the Spring Boot web application. When the application starts, beans, ​and settings are wired up dynamically. They are applied to the application context. The code for HelloWorldApp class is shown below:HelloWorldApp

Run Command

package helloworld;
import java.util.Arrays;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
 
@SpringBootApplication
public class HelloWorldApp {
     
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(HelloWorldApp.class, args);
         
        System.out.println("Inspecting the beans");
         
        String[] beans = ctx.getBeanDefinitionNames();
        Arrays.sort(beans);
        for (String name : beans) {
            System.out.println("Bean Name" +name);
        }
    }
 
}

Maven is used for building the application. The command below builds the application.

Maven Build Command

mvn package

The output of the executed command is shown below.

spring framework components - Maven Command
Maven Command – Spring

The jar file spring-helloworld-0.1.0.jar is created. The following command is used for executing the jar file.

Java Command

java -jar target/spring-helloworld-0.1.0.jar

The output of the Java command is shown as below:

spring framework components - Hello World Beans
Spring Hello World Beans

Curl command is invoked on the command line for the execution of index method. The method returns a String “Hello World” text. @RestController aggregates the two annotations @Controller and @ResponseBody. This results in returning data. The ouput is shown as below.

spring framework components - Curl Command
Curl Command – Spring

2.9 Unit Tests

2.9.1 Spring

In Spring, MockMvc is used to send HTTP requests to the DispatcherServlet. The assertions are made based on the result obtained from the servlet. @AutoConfigureMockMvc annotation is used with @SpringBootTest to inject a MockMvc instance. The implementation of the Spring Unit Test is shown as below:

HelloWorldControllerTest

package helloworld;
 
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
 
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloWorldControllerTest {
 
    @Autowired
    private MockMvc mvc;
 
    @Test
    public void getMessage() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("Hello World\n")));
    }
}

Maven command is used to run the unit test. The command is as below :Maven Build Command

Maven Build Command

mvn package

The output of the executed command is shown below.

spring framework components - unit test
Spring Unit Test

2.10 Best Practices

In spring framework, the developer can implement custom annotation by implementing ConstraintValidator. Custom Annotations help in enhancing the separation of concerns. The developer can use a declarative way of implementing custom validators. You can use annotations like AutoWired and Resource in spring framework classes. Hibernate provides different query classes. The developer​ can pick the right query class based on the context. Bind Parameters are used to map the parameters to the right types. ​The developer​ can analyze the queries and optimize them for performance.

2.11 Error Handling

Spring framework has features to handle exceptions and errors. Errors in REST APIs help in presenting the issues to the clients.

2.12 Performance

Spring framework has features like extending the AbstractMonitoringInterceptor class to log the start, end, and duration of a method. Spring AOP helps in defining and writing code which can intercept the execution of the methods for monitoring the performance.

2.13 Scalability

Spring framework has MVC, ORM, Messaging and Caching support which is very important for scalability. For scalable deployments, developers and architects need to ensure the servers are stateless or implement sticky sessions with load balancers. Caching helps in reducing the load on the database.

2.14 Reliability

Spring Boot has a reliable application development framework. SpringBoot applications are deployed as self-contained units using the profiles feature.

2.15 Security

Spring Security for User interfaces and HTTP back ends is based on Servlet Filters. The spring framework provides support for implementing access rules to methods. Spring Security framework has an architecture which is designed to support both authentication and authorization.

2.16 Logging

Spring Framework uses Commons Logging for application logging. Different configurations for logging are provided in the framework. They are Java Util Logging, Log4J2, and Logback. Loggers are pre-configured for printing the output on the console or in the configured file.

2.17 Management

Spring management features help in configuring a custom port, management server, and SSL configuration management. Spring Boot Actuator configures the enabled HTTP endpoints. Spring framework provides management endpoints which are JMX MBeans.

2.18 Deployment

The Spring Server supports the deployment of applications packaged in the formats such as Raw OSGi Bundles, Java EE WAR, Web Bundles, PAR, and Plans.

3. Download the Source Code

That was a tutorial about the Spring framework components.

Download
You can download the full source code of this example here: Spring Framework Components Tutorial

Bhagvan Kommadi

Bhagvan Kommadi is the Founder of Architect Corner & has around 20 years’ experience in the industry, ranging from large scale enterprise development to helping incubate software product start-ups. He has done Masters in Industrial Systems Engineering at Georgia Institute of Technology (1997) and Bachelors in Aerospace Engineering from Indian Institute of Technology, Madras (1993). He is member of IFX forum,Oracle JCP and participant in Java Community Process. He founded Quantica Computacao, the first quantum computing startup in India. Markets and Markets have positioned Quantica Computacao in ‘Emerging Companies’ section of Quantum Computing quadrants. Bhagvan has engineered and developed simulators and tools in the area of quantum technology using IBM Q, Microsoft Q# and Google QScript. He has reviewed the Manning book titled : "Machine Learning with TensorFlow”. He is also the author of Packt Publishing book - "Hands-On Data Structures and Algorithms with Go".He is member of IFX forum,Oracle JCP and participant in Java Community Process. He is member of the MIT Technology Review Global Panel.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button