Introduction to Spring Architecture
src : https://spring.io/

Introduction to Spring Architecture

9 min read

Spring framework is a lightweight yet powerful Java framework which is used for application development. It provides support for developing Java applications and handles the infrastructure configuration, letting the developer focus on business logic (What more could a developer want, right?). The fact that Spring promises modularity, makes it a famous framework among developers.

Modularity is the ability to use only the modules that are needed without worrying about using the other modules.

The best part about Spring being modular is that the modules can be used according to the use case/ need of the product/ developers (can’t miss out any, can we?). Spring has modules like Spring AOP, Spring messaging, Spring Transaction, Spring Data Access, etc which provide a diverse range of services. The Spring Core module provides the base implementation on top of which these modules can be utilised.



A Brief History Lesson…

Before understanding the different features the framework is built upon , let us have a quick history lesson on our much (or soon to become) favourite topic. An Open source Framework, Spring was written by Rod Johnson and was first released in June 2002. It was built with the purpose of overcoming a number of major complexities with Java EE and Enterprise Java Beans by using a simpler solution (now affectionately known as Spring Framework) which is based on the use of POJOs( explained further in the article), Dependency Injection and Inversion of Control.

What is Java Enterprise Edition and EJB? Java EE is used to develop enterprise apps. EJB is a specification of Java EE for server side architecture. One of the first technologies to make the development of server side enterprise applications easier, it handles myriad of concerns like implementation of concurrency, transaction management, etc.



Drawbacks of applications built without Spring:

  • A lot of configurations were needed — it was proving to be a performance bottleneck, slowing down applications.
  • code could become complicated with increasing XML files
  • applications could become heavy, affecting the performance of the system
  • hard coding dependencies for each component made the development experience frustrating

Over the years , Spring has become a favourite among many developers as it has not only solved the above problems, but provided a higher learning curve, providing ease of development with its organised packages and classes, and a variety of other features.



And Beyond...

Some concepts that Spring Framework is based upon

  1. Dependency Injection It is an implementation of Inversion of Control where instead of hardcoding the objects and their dependencies, the dependencies are simply specified via external configuration files, annotations or java code. The objects which have been registered during the startup of the container are injected at compile time only whenever they are required. Different ways to implement Dependency Injection are:
  2. Using Setters
  3. Using Constructors
  4. Field Based

Dependency Injection Example
Dependency Injection Example

The above example shows three different ways to implement Dependency Injection. Annotation based configuration has been used where we first define a Configuration class that will be used to define and inject the bean. @Bean annotation is used to let Spring framework know that the method defined with this annotation should be used to get the bean implementation to inject in Component classes. @Autowired allows constructor-based, field-based or setter dependency injection.

Annotations are tags which are used to represent the metadata associated with interfaces, classes, methods or fields to provide some additional information about them. Some commonly used annotations in Spring include — @Component ( a Java class annotated with @Component is found during classpath scanning and registered in the container as a Spring bean).@Controller, @Service ,@Repository are special cases of the component annotation which are used to define different types of components.

  1. Inversion of Control

Inversion of Control introduces the concept of letting the Spring Framework container handle the creation of objects instead of the developer instantiating the object every time they are needed. This makes the objects loosely coupled.

This is a design framework which inverts the flow of control i.e it enables a container to manage the lifecycle of an object. This can be further explained by looking into a piece of software where the logical components which interact with each other are instances of classes (objects) and depend on one another. Invocation of one object may lead to the invocation of other objects , leading to these objects being tightly coupled.

The IoC container instantiates the application class, configures the objects and assembles the dependencies between the objects according to the information received by it through annotations, configuration files or java code.

Spring Framework allows the container to manage lifecycle of various processes. All the developers need to do to make this work is write some code to register the classes/objects using annotations, external configuration files, etc and the rest is by Spring ( from creation to destruction of the object).

Example of tightly coupled objects
Example of tightly coupled objects

In the following example the FoodMaker class is tightly coupled with the Ingredient class to perform makeFood(). In this case the parent object knows more about the child object and the child object cannot be changed by anyone except the parent class introducing a dependency, making it tightly coupled.

Example of loosely coupled objects
Example of loosely coupled objects

In the above example FoodMaker gets the Ingredient object from external sources, in this case the Spring container (using dependency injection). This makes the objects independent of each other.

  1. Using POJOs

POJOs are Java Objects containing properties, their getters and setters and certain methods(like to String which can be overridden) .

There are no restrictions on the scope of the properties (they can be public, private, protected with public getters and setters.) . They do not extend any pre-specified classes, interfaces or annotations and are exclusive of all frameworks. Further, Java Beans are special kinds of POJOs which must implement Serialisable interface. The fields should be private with getters, setters or both. These fields can be accessed only through getters or setters.The use of Plain Old Java Objects make the Java Program more readable and reusable.

Example of a POJO
Example of a POJO



SPRING ARCHITECTURE

Spring Architecture
Source:https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/images/spring-overview.png

The architecture of Spring framework comprises of several modules which are built on top of the core container and can be utilised according to need of the developer. This feature of modularity allows Spring to integrate with other frameworks as well.

  1. Core Container

This module is responsible for creating and managing beans along with their dependencies

The Spring Core and Spring Bean modules provide the means to implement Dependency Injection. It allows the object to define its dependencies. Whenever a bean is created, the container injects those dependencies. BeanFactory (which is an implementation of factory pattern) allows to decouple the configuration and specification of object dependencies from the actual business logic of the program.

The Spring Context module is built upon the Spring Core and Bean module. It provides a mean to access the objects that have been defined and configured in the Spring container. The module is responsible for providing various enterprise level services like internationalisation, support for scheduling, caching etc. The Application Context (container defined by ApplicationContext interface) is an integral part of the Context module. It can load bean definitions, wire beans together and provide functionalities like reading messages from a properties file or publishing application events.

The Spring Expression Module is an expression language which enables runtime manipulation and querying of objects. It can be used with annotation or XML based configurations.

  1. Spring Data Access/Integration

This module is responsible for providing integration with various data access mechanisms / frameworks and communication with data sources.

Spring JDBC (Java Database Connectivity) is an API which helps the client to access a database and perform operations on it using Statements, Queries, ResultSets. The complexity related to this is removed using JDBCTemplate which allows easy access, iteration and mapping of data.

Spring ORM (Object Relational Mapping) frameworks map a java object to a database table using an ORM API. Some ORM frameworks are Hibernate, JPA ,etc. Spring ORM provides integration with these frameworks.

Spring JMS (Java Messaging Service) defines specification for producing and consuming messages (pub-sub communication). Spring JMS provides an abstraction over JMS implementations like ActiveMQ, RabbitMQ.

Spring OXM (Object XML Marshalling) defines specifications to transfer and access data in form of XML. Spring OXM provides abstraction over Java using OXM implementations like JAXB .

Spring Transactions provides a support for transaction management of classes.

  1. Web

Responsible for providing a base for building web applications and integration with other MVC frameworks like Struts, JSF ,etc

Spring-Web modules provides web oriented integration features.

Spring Web MVC module is used to create web applications. It enforces a design pattern which allows a single point of entry — the DispatcherServlet, which acts as the Front Controller and forwards the request to other objects for processing. Different concerns are separated into different layers- Model, View and Controller, which helps in building a loosely coupled application. Model is the application data, View is used to render the response to end user using the model and Controller is responsible for processing the request, generating a model and selecting the view based on the model.

Spring Web-Socket module provides support for building Web Sockets with spring, enabling bidirectional communication socket between client and servers so that server can also push messages directly to the clients.

Spring Web-Portlet helps in the easier development of Portlets and use the same concept as Spring MVC with a Dispatcher Portlet(Dispatcher servlet in the case of Spring MVC), front controller, handler mappings, controllers, views and model.

  1. AOP

Aspect Oriented Programming provides modularity like Object Oriented Programming does. The key difference between both is that a class is the unit of modularity in OOPs whereas an aspect is the unit of modularity in AOP .

AOP breaks the program logic into distinct parts using cross cutting concerns which are features that affect the whole application and are not specific to business logic. AOP can be used for logging, exception handling, implementing security, etc. AOP can be implemented with Spring using XML based configurations or annotations with AspectJ, which is a very popular way to implement AOP nowadays.

  1. Instrumentation

Spring Instrumentation enables the developers to monitor the performance, track and trace code, its errors and the related information . Spring supports instrumentation through AOP and Logging in various environments.

  1. Test

Spring test module helps in easy unit testing with JUnit, TestNG as well as integration testing. Mock objects can also be used to unit test the code in isolation.

  1. Messaging

It serves as a foundation to implement messaging based applications.



Conclusion

The Spring framework has evolved into an efficient and developer friendly framework with its modular architecture and a very active community of developers. Spring can be used to develop applications in an easy , flexible and secure manner. So when in doubt…GO TEAM SPRING!