Spring


Spring is a powerful lightweight application development framework used for Java Enterprise Edition (JEE). It provides support to various frameworks such as Struts, Hibernate, EJB, JSF etc.
Features of Spring Framework
  • Lightweight: Spring Framework is lightweight with respect to size and transparency. 
  • Inversion of Control (IOC): In Spring Framework, loose coupling is achieved using Inversion of Control. The objects give their own dependencies instead of creating or looking for dependent objects.
  • Aspect Oriented Programming (AOP): By separating application business logic from system      services, Spring Framework supports Aspect Oriented Programming and enables cohesive development.
  • Container: Spring Framework creates and manages the life cycle and configuration of application objects.
  • MVC Framework: Spring Framework is a MVC web application framework. This framework is configurable via interfaces and accommodates multiple view technologies.
  • Transaction Management: For transaction management, spring framework provides a generic      abstraction layer.
  • JDBC Exception Handling: The JDBC abstraction layer of the Spring Framework offers an exception hierarchy, which simplifies the error handling strategy.
  • Declarative support: It provides declarative support for caching, validation, transactions and formatting.

Advantages of Using Spring Framework

  • Works on POJO’s (Plain Old Java Object) which makes your application lightweight.
  • Provides predefined templates for JDBC, Hibernate, JPA etc., thus reducing your effort of writing too much code.
  • Because of dependency injection feature, your code becomes loosely coupled.
  • Using Spring Framework, the development of Java Enterprise Edition applications became faster.
  • It provides declarative support for transactions, validation, caching and formatting.

Spring Framework Architecture



Core Container
This container has the following four modules:
  1. Spring Core: This module is the core of the Spring Framework. It provides implementation for      features like IoC (Inversion of Control) and Dependency Injection with singleton design pattern.
  2. Spring Bean: This module provides implementation for the factory design pattern through BeanFactory.
  3. Spring Context: This module is built on the solid base provided by the Core and the Beans modules and is a medium to access any object defined and configured.
  4. Spring Expression Languages (SpEL): This module is an extension to expression language supported by Java server pages. It provides a powerful expression language for querying and manipulating an object graph, at runtime.
Spring Data Access/ Integration
  1. JDBC: This module provides JDBC abstraction layer which eliminates the need of repetitive and unnecessary exception handling overhead.
  2. ORM: ORM stands for Object Relational Mapping. This module provides consistency/ portability to our code regardless of data access technologies based on object oriented mapping concept.
  3. OXM: OXM stands for Object XML Mappers. It is used to convert the objects into XML format and vice versa. The Spring OXM provides an uniform API to access any of these OXM frameworks.
  4. JMS: JMS stands for Java Messaging Service. This module contains features for producing and consuming messages among various clients.
  5. Transaction: This module supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs. All the enterprise level transaction implementation concepts can be implemented in spring by using this module.
Spring Web
Web: This module using servlet listeners and a web-oriented application context, provides basic web-oriented integration features like multi-part file upload functionality and the initialization of the IoC container.
  1. Servlet / Web-Servlet: This module contains Model-View-Controller (MVC) based implementation for web applications. It provides all other features of MVC, including UI tags and data validations. 
  2. Struts: This module provides the support for the struts framework.
  3. Web-Portlet: This module is also known as Spring-MVC-Portlet module. It provides the support for spring based Portlets and mirrors the functionality of a Web-Servlet module.
Aspect Oriented Programming (AOP)
AOP language is a powerful tool which allows developers to add enterprise functionality to the application such as logging, transaction, security etc. It allows us to write less code and separate the code logic. AOP uses cross-cutting concerns.
Instrumentation
This module provides class instrumentation support and class loader implementations that are used in certain application servers.
Test
This module supports the testing of Spring components with JUnit or TestNG. It provides consistent loading of Spring ApplicationContexts and caching of those contexts. It also provides mock objects that we can use to test our code in isolation.


Spring - IoC Containers

The Spring container is at the core of the Spring Framework. The container will create the objects, wire them together, configure them, and manage their complete life cycle from creation till destruction. The Spring container uses DI to manage the components that make up an application. These objects are called Spring Beans.

Spring provides the following two distinct types of containers.

Sr.No.
Container & Description
1
This is the simplest container providing the basic support for DI and is defined by the org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purpose of backward compatibility with a large number of third-party frameworks that integrate with Spring.
2
This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. This container is defined by the org.springframework.context.ApplicationContext interface.
The ApplicationContext container includes all functionality of the BeanFactorycontainer

Spring - Bean Scopes


Sr.No.
Scope & Description
1
singleton
This scopes the bean definition to a single instance per Spring IoC container (default).
2
prototype
This scopes a single bean definition to have any number of object instances.
3
request
This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
4
session
This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
5
global-session
This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
6
RefreshScope
This RefreshScope on some beans which can be only initialized once. This is used when some configuration changes, suppose d burl changed.
Example:
@Bean
@Scope("singleton")
public Person personSingleton() {
    return new Person();
}
Or we can use constant instead of the String value
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
Inversion of control: - It’s a generic term and implemented in several ways (events, delegates, DI etc).



Dependency Injection

Dependency Injection is also one of the core concepts of Spring Framework. It is a design pattern that removes the dependency from the code. That is, the Spring Framework provides the dependencies of the class itself so that it can be easy to manage and test the application. You can provide information from external source such as XML file. Here, you do not create the objects instead you just define how they should be created and IoC container will create the objects for you.
In spring, dependencies can be injected in two ways:
  1. By constructor
  2. By setter method

By setter Method : Here is the content of TextEditor.java file −
package com.sathish;
import org.springframework.beans.factory.annotation.Autowired;

public class TextEditor {
   private SpellChecker spellChecker;

   @Autowired
   public void setSpellChecker( SpellChecker spellChecker ){
      this.spellChecker = spellChecker;
   }
   public SpellChecker getSpellChecker( ) {
      return spellChecker;
   }
   public void spellCheck() {
      spellChecker.checkSpelling();
   }
}
Following is the content of another dependent class file SpellChecker.java:
package com.sathish;

public class SpellChecker {
   public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   public void checkSpelling(){
      System.out.println("Inside checkSpelling." );
   }
}

By constructor: Here is the content of TextEditor.java file
package com.sathish;

import org.springframework.beans.factory.annotation.Autowired;

public class TextEditor {
   private SpellChecker spellChecker;

   @Autowired
   public TextEditor(SpellChecker spellChecker){
      System.out.println("Inside TextEditor constructor." );
      this.spellChecker = spellChecker;
   }
   public void spellCheck(){
      spellChecker.checkSpelling();
   }
}

Spring AOP
The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.

AOP Terminologies:
Before we start working with AOP, let us become familiar with the AOP concepts and terminology. These terms are not specific to Spring, rather they are related to AOP.
Terms
Description
Aspect
A module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement.
Join point
This represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework.
Advice
This is the actual action to be taken either before or after the method execution. This is actual piece of code that is invoked during program execution by Spring AOP framework.
Pointcut
This is a set of one or more join points where an advice should be executed. You can specify pointcuts using expressions or patterns as we will see in our AOP examples.
Introduction
An introduction allows you to add new methods or attributes to existing classes.
Target object
The object being advised by one or more aspects, this object will always be a proxied object. Also referred to as the advised object.
Weaving
Weaving is the process of linking aspects with other application types or objects to create an advised object. This can be done at compile time, load time, or at runtime.

Types of Advice
Spring aspects can work with five kinds of advice mentioned below:
Advice
Description
Before
Run advice before the method execution.
After
Run advice after the method execution regardless of its outcome.
after-returning
Run advice after the method execution only if method completes successfully.
after-throwing
Run advice after the method execution only if method exits by throwing an exception.
Around
Run advice before and after the advised method is invoked.

Example:
package com.sathish;
 
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
 
@Aspect
public class Logging {
   /* Following is the definition for a pointcut to select all the 
methods available
   */
   @Pointcut("execution(* com.sathish.*.*(..))")
   private void logAll(){}
 
   /* This is the method I would like to execute before a selected 
method execution.
   */
   @Before("logAll()")
   public void beforeAdvice(){
      System.out.println("Going to call business logic method");
   }
 
   @After("logAll()")
   public void afterAdvice(){
      System.out.println("End of business logic method");
   }
 
   @AfterReturning(pointcut = "logAll()", returning = "retVal")
   public void afterReturningAdvice(Object retVal){
      System.out.println("Returning:" + retVal.toString() );
   }
 
   @AfterThrowing(pointcut = "logAll()", throwing = "e")
   public void AfterThrowingAdvice(IllegalArgumentException e){
      System.out.println("There has been an exception:"+e.toString());   
   }
}

 

Spring MVC (Model-View-Controller)

Spring MVC helps in building flexible and loosely coupled web applications. The Model-View-Controller design pattern helps in separating the business logic, presentation logic and navigation logic. It provides an elegant solution to use MVC in Spring Framework with the help of DispatcherServlet.

When a request is sent to the Spring MVC Framework, the following takes place.
  • A request is received by DispatcherServlet.
  • The DispatcherServlet communicates with HandlerMapping and calls the Controller associated with the request.
  • The request is processed by the Controller by calling the appropriate service methods and a ModelAndView object to the DispatcherServlet is returned. 
  • The view name is sent to a ViewResolver by the DispatcherServlet to find the actual View to invoke.
  • Now the model object DispatcherServlet is passed to View to render the result.
  • With the help of the model data, the View renders the result back to the user.

Spring - JDBC Framework

The JDBC Template executes SQL queries, updates statements, stores procedure calls, performs iteration over ResultSets, and extracts returned parameter values. It also catches JDBC exceptions and translates them to the generic, more informative.
Instances of the JdbcTemplate class are threadsafe once configured. So you can configure a single instance of a JdbcTemplate and then safely inject this shared reference into multiple DAOs.
A common practice when using the JDBC Template class is to configure a DataSource in your Spring configuration file, and then dependency-inject that shared DataSource bean into your DAO classes, and the JdbcTemplate is created in the setter for the DataSource.
Inserting a row into the table
String SQL = "insert into Employee (name, id) values (?, ?)";
jdbcTemplateObject.update( SQL, new Object[]{"sam", 11} );
Updating a row into the table
String SQL = "update Employee set name = ? where id = ?";
jdbcTemplateObject.update( SQL, new Object[]{"sam", 10} );
Deleting a row from the table
String SQL = "delete Employee where id = ?";
jdbcTemplateObject.update( SQL, new Object[]{20} );

Example Snippet
package com.sathish;
 
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
 
public class EmployeeJDBCTemplate implements EmployeeDAO {
   private DataSource dataSource;
   private JdbcTemplate jdbcTemplateObject;
   
   public void setDataSource(DataSource dataSource) {
      this.dataSource = dataSource;
      this.jdbcTemplateObject = new JdbcTemplate(dataSource);
   }
   public void create(String name, Integer id) {
      String SQL = "insert into Employee (name, id) values (?, ?)";
      jdbcTemplateObject.update( SQL, name, id);
      System.out.println("Created Record Name = "+name+ " Id = " + id);
      return;
   }
   public Employee getEmployee(Integer id) {
      String SQL = "select * from Employee where id = ?";
      Employee employee = jdbcTemplateObject.queryForObject(SQL, 
         new Object[]{id}, new EmployeeMapper());
      
      return employee;
   }
   public List<Employee> listEmployees() {
      String SQL = "select * from Employee";
      List <Employee> employees = jdbcTemplateObject.query(SQL, 
new EmployeeMapper());
      return employees;
   }
   public void delete(Integer id) {
      String SQL = "delete from Employee where id = ?";
      jdbcTemplateObject.update(SQL, id);
      System.out.println("Deleted Record with ID = " + id );
   }
   public void update(Integer id, String name){
      String SQL = "update Employee set name = ? where id = ?";
      jdbcTemplateObject.update(SQL, name, id);
      System.out.println("Updated Record with ID = " + id );
   }
}

JDBCTemplate can be used on dynamic SQl as well as stored procedures.

Spring - Transaction Management

A database transaction is a sequence of actions that are treated as a single unit of work. These actions should either complete entirely or take no effect at all. Transaction management is an important part of RDBMS-oriented enterprise application to ensure data integrity and consistency. The concept of transactions can be described with the four key properties described as ACID

A real RDBMS database system will guarantee all four properties for each transaction. The simplistic view of a transaction issued to the database using SQL is as follows −
·      Begin the transaction using begin transaction command.
·      Perform various deleted, update or insert operations using SQL queries.
·      If all the operation are successful then perform commit otherwise rollback all the operations.

Programmatic vs. Declarative

Spring supports two types of transaction management
·      Programmatic transaction management: This means that you have to manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
·      Declarative transaction management: This means you separate transaction management from the business code. You only use annotations or XML-based configuration to manage the transactions.
Programmatic Transaction management example snippet:
private PlatformTransactionManager transactionManager;
TransactionDefinition defination = new DefaultTransactionDefinition();
TransactionStatus status = transactionManager.getTransaction(defination);
 
try {
     String SQL = "insert into Employee (name, id) values (?, ?)";
     jdbcTemplateObject.update( SQL, name, id);
     System.out.println("Inserted Name = " + name + ", id = " + id);
     transactionManager.commit(status);
    } 
catch (DataAccessException e) {
    System.out.println("Error in creating record, rolling back");
    transactionManager.rollback(status);
    throw e;
}

Declarative Transaction management example snippet:
//On the configuration class we need to add @EnableTransactionManagement
//We need to create transaction manager bean
@Bean
  public PlatformTransactionManager transactionManager() {
      DataSourceTransactionManager transactionManager = new 
DataSourceTransactionManager();
      transactionManager.setDataSource(dataSource());
      return transactionManager;
  }
//finally we need to annotate @Transactional
@Transactional
public interface OrderService {
 
    void persistOrders(List<OrderItem> orderItems);
 
    List<OrderItem> getAllOrders();
}

Following are the possible values for isolation level
Sr.No
Isolation & Description
1
TransactionDefinition.ISOLATION_DEFAULT
This is the default isolation level.
2
TransactionDefinition.ISOLATION_READ_COMMITTED
Indicates that dirty reads are prevented; non-repeatable reads and phantom reads can occur.
3
TransactionDefinition.ISOLATION_READ_UNCOMMITTED
Indicates that dirty reads, non-repeatable reads, and phantom reads can occur.
4
TransactionDefinition.ISOLATION_REPEATABLE_READ
Indicates that dirty reads and non-repeatable reads are prevented; phantom reads can occur.
5
TransactionDefinition.ISOLATION_SERIALIZABLE
Indicates that dirty reads, non-repeatable reads, and phantom reads are prevented.

Following are the possible values for propagation types
Sr.No.
Propagation & Description
1
TransactionDefinition.PROPAGATION_MANDATORY
Supports a current transaction; throws an exception if no current transaction exists.
2
TransactionDefinition.PROPAGATION_NESTED
Executes within a nested transaction if a current transaction exists.
3
TransactionDefinition.PROPAGATION_NEVER
Does not support a current transaction; throws an exception if a current transaction exists.
4
TransactionDefinition.PROPAGATION_NOT_SUPPORTED
Does not support a current transaction; rather always execute nontransactionally.
5
TransactionDefinition.PROPAGATION_REQUIRED
Supports a current transaction; creates a new one if none exists.
6
TransactionDefinition.PROPAGATION_REQUIRES_NEW
Creates a new transaction, suspending the current transaction if one exists.
7
TransactionDefinition.PROPAGATION_SUPPORTS
Supports a current transaction; executes non-transactionally if none exists.
8
TransactionDefinition.TIMEOUT_DEFAULT
Uses the default timeout of the underlying transaction system, or none if timeouts are not supported.

Spring Batch
·       Spring batch is based on spring framework and is very lightweight. The core concept of spring batch as the name suggests is processing of data in batches.
·       Spring Batch provides advance services and features for high volume and high performance batch jobs using optimization and partitioning techniques. It is highly scalable and can be used for processing of high amount of data.

Spring Batch Usage

A batch program reads a large number of records from a database, file, or queue, processes the data based on the business needs, and then writes back data in the desired form.

Spring Batch automates this basic batch iteration, providing the capability to process similar transactions as a set, all this can be done in an offline environment without any user interaction.

Spring Batch Architecture

The diagram below shows the technical architecture of Spring Batch.

1.     Application: This contains all the batch jobs and code written by the developer based on business needs.
2.     Batch Core: It contains the runtime classes necessary to run a batch job. The classes such are JobLauncher, Job and Step implementation are part of the Batch Core.
3.     Batch Infrastructure: This contains the reader and writer services which are used by developer and the framework itself. The classes are ItemReader and ItemWriter. It also contains services to retry read and write.

Spring Batch Job consists of the following main components:
·       Job: A Job represents the Spring Batch job. Each job can have one or more steps
·       Step: A Step that delegates to a Job to do its work. This is a great tool for managing the dependencies between the jobs, and also to modularize the complex step logic into something that is testable in the isolation. The job is executed with parameters that can be extracted from the step execution, hence this step can also be usefully used as the worker in a parallel or partitioned execution
·       ItemReader: It is a strategy interface for providing the data. The implementation here is expected to be stateful and it will be called multiple times for each batch. Each one can call to the read() method that will return a different value and finally returning the null when all input data is exhausted
·       ItemProcessor: It is an interface for item transformations. Given an item as an input, this interface provides an extension point which allows the application to implement its business logic in an item oriented processing scenario
·       ItemStreamWriter: It is an interface for the generic output operations. The class implementing this interface will be responsible for serializing the objects as necessary. Generally, it is the responsibility of the implementing class to decide which technology to use for mapping and how it should be configured. The write() method is responsible for making sure that any internal buffers are flushed and if a transaction is active it will also be necessary to discard the output on a subsequent rollback. The resource to which the writer is sending the data should normally be able to handle this itself





No comments:

Post a Comment