Search This Blog

Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Thursday 16 July 2020

Spring Framework Overview


Spring makes it easy to create Java enterprise applications. It provides everything you need to embrace the Java language in an enterprise environment, with support for Groovy and Kotlin as alternative languages on the JVM, and with the flexibility to create many kinds of architectures depending on an application’s needs. Spring supports a wide range of application scenarios. Spring is open source. It has a large and active community that provides continuous feedback based on a diverse range of real-world use cases. The Spring Framework is divided into modules. Applications can choose which modules they need. At the heart are the modules of the core container, including a configuration model and a dependency injection mechanism. Beyond that, the Spring Framework provides foundational support for different application architectures, including messaging, transactional data and persistence, and web. It also includes the Servlet-based Spring MVC web framework and, in parallel, the Spring WebFlux reactive web framework. Spring came into being in 2003 as a response to the complexity of the early J2EE specifications. While some consider Java EE and Spring to be in competition, Spring is, in fact, complementary to Java EE. The Spring programming model does not embrace the Java EE platform specification; rather, it integrates with carefully selected individual specifications from the EE umbrella The Spring Framework also supports the Dependency Injection (JSR 330) and Common Annotations (JSR 250) specifications, which application developers may choose to use instead of the Spring-specific mechanisms provided by the Spring Framework.

Thursday 27 April 2017

Spring AOP – Advice

Spring AOP – Advice

Spring AOP Advice is the action taken by an aspect at a particular join point. Different types of advice include 
  • Around advice
  • Before advice
  • After advice

Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors around the join point.

Types of advice:
  • Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point.

  • After returning advice: Advice to be executed after a join point completes normally.

  • After throwing advice: Advice to be executed if a method exits by throwing an exception.

  • After (finally) advice: Advice to be executed regardless of the means by which a join point exits, normal or exceptional return.

  • Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

Tuesday 25 April 2017

Aspect Oriented Programming with Spring

Aspect Oriented Programming with Spring

Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects. One of the key components of Spring is the AOP framework. While the Spring IoC container does not depend on AOP, meaning you do not need to use AOP if you don't want to, AOP complements Spring IoC to provide a very capable middleware solution. Aspect-Oriented Programming requires breaking down program logic into distinct parts called concerns. 

The functions that span multiple points of an application are called cross-cutting concerns and these cross-cutting concerns are conceptually separate from the application's business logic. Examples of aspects are logging, auditing, declarative transactions, security, caching, etc. Spring AOP module provides interceptors to intercept an application. For example, when a method is executed, you can add extra functionality before or after the method execution.


AOP is used in the Spring Framework to

Provide declarative enterprise services, especially as a replacement for EJB declarative services. 
Allow users to implement custom aspects, complementing their use of OOP with AOP.

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.
Aspect: a modularization of a concern that cuts across multiple classes. Transaction management is a good example of a crosscutting concern in Java EE applications. In Spring AOP, aspects are implemented using regular classes  or regular classes annotated with the @Aspect annotation.
Join point: a point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.
Advice: action taken by an aspect at a particular join point. Different types of advice include "around," "before" and "after" advice
Pointcut: a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut.
Introduction: declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces to any advised object. 
Target object: object being advised by one or more aspects. Also referred to as the advised object. 
AOP proxy: an object created by the AOP framework in order to implement the aspect contracts. In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy.
Weaving: 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. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.

Friday 21 April 2017

Spring Dependencies

Spring Dependencies


An application will have certain objects that work together to present what the end-user sees as a coherent application. We can define a number of bean definitions that are stand-alone, each to themselves, to a fully realized application where objects work (or collaborate) together to achieve some goal.

Injecting Dependencies
It becomes evident upon usage that code gets much cleaner when the DI principle is applied, and reaching a higher grade of decoupling is much easier when beans do not look up their dependencies, but are provided with them.

Setter Injection
Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

public class SimpleMovieLister {
// the SimpleMovieLister has a dependency on the MovieFinder
    private MovieFinder movieFinder;
// a setter method so that the Spring container can 'inject' a MovieFinder
    public void setMovieFinder
        (MovieFinder movieFinder) {
      this.movieFinder = movieFinder;
    }
}

Constructor Injection
Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator. Additionally, calling a static factory method can be considered almost equivalent.

public class SimpleMovieLister {
    // the SimpleMovieLister has a dependency on the MovieFinder
    private MovieFinder movieFinder;
    // a constructor so that the Spring container can 'inject' a MovieFinder
    public SimpleMovieLister
       (MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }
    }

Constructor or Setter DI?
·         Setter based DI makes objects of that class responsive to being re-configured (or re-injected) at some later time.

·         Constructor-injection supplying all of an object's dependencies means that that object is never returned to client (calling) code in a less than totally initialized state.

Spring Expression Language (SpEL)

Spring Expression Language (SpEL)

The Spring Expression Language (SpEL) is a powerful expression language that supports querying and manipulating an object graph at runtime. The language syntax is similar to Unified EL but offers additional features, most notably method invocation and basic string templating functionality.
The Spring Expression Language was created to provide the Spring community with a single well supported expression language that can be used across all the products in the Spring portfolio. SpEL is based on an technology agnostic API allowing other expression language implementations to be integrated should the need arise.
While SpEL serves as the foundation for expression evaluation within the Spring portfolio, it is not directly tied to Spring and can be used independently.
The expression language supports the following functionality
  • Literal expressions
  • Boolean and relational operators
  • Regular expressions
  • Class expressions
  • Accessing properties, arrays, lists, maps
  • Method invocation
  • Relational operators
  • Assignment
  • Calling constructors
  • Ternary operator
  • Variables
  • User defined functions
  • Collection projection
  • Collection selection
  • Templated expressions

The EvaluationContext interface


The interface EvaluationContext is used when evaluating an expression to resolve properties, methods, fields, and to help perform type conversion. The StandardEvaluationContext is where you specify the root object to evaluate against via the method setRootObject or passing the root object into the constructor. . You can also specify variables and functions that will be used in the expression using the methods setVariable and registerFunction. The StandardEvaluationContext is also where you can register custom ConstructorResolvers, MethodResolvers, and PropertyAccessors to extend how SpEL evaluates expressions.

Type Conversion


By default SpEL uses the conversion service available in Spring core (org.springframework.core.convert.ConversionService). This conversion service comes with many converters built in for common conversions but is also fully extensible so custom conversions between types can be added. Additionally it has the capability that it is generics aware. This means that when working with generic types in expressions, SpEL will attempt conversions to maintain type correctness for any objects it encounters.

Friday 14 April 2017

Spring Modules

Spring Modules


The Spring Framework contains a lot of features, which are well-organized in about twenty modules. These modules can be grouped together based on their primary features into 
Ø  Core Container 
Ø  Data Access/Integration 
Ø  Web 
Ø  AOP (Aspect Oriented Programming) 
Ø  Instrumentation 
Ø  Test

Core Container Module
The Core Container consists of the Core, Beans, Context and Expression modules.

The Core and Beans modules provide the most fundamental parts of the framework and provides the IoC and Dependency Injection features.

The Context module build on top of the Core and Beans modules. The Context module inherits its features from the Beans module and adds support for internationalization (I18N), event-propagation, resource-loading, and the transparent creation of contexts. The ApplicationContext interface is the focal point of the Context module that provides these features.

The Expression Language module provides a powerful expression language for querying and manipulating an object graph at runtime. The language supports setting and getting of property values, property assignment, method invocation, accessing the context of arrays, collections and indexers, logical and arithmetic operators, named variables, and retrieval of objects by name from Spring's IoC container.

Data Access/Integration Module
The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules.

The JDBC module provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes.

The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis.

The OXM module provides an abstraction layer for using a number of Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream.

The JMS module provides Spring's support for the Java Messaging Service. It contains features for both producing and consuming messages.

The Transaction module provides a way to do programmatic as well as declarative transaction management, not only for classes implementing special interfaces, but for all your POJOs.

Web Module
The Web layer consists of the Web, Web-Servlet and Web-Portlet modules.

Spring's Web module provides basic web-oriented integration features, such as multipart file-upload functionality, the initialization of the IoC container using servlet listeners and a web-oriented application context.

The Web-Servlet module provides Spring's Model-View-Controller (MVC) implementation for web-applications

The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors what is provided in the Web-Servlet module.

AOP and Instrumentation Module
Spring's AOP module provides an aspect-oriented programming implementation allowing you to define, method-interceptors and pointcuts to cleanly decouple code implementing functionality that should logically be separated.

The Instrumentation module provides class instrumentation support and classloader implementations to be used in certain application servers.

Test Module

The Test module contains the Test Framework that supports testing Spring components using JUnit or TestNG. 

Spring Modules

Thursday 13 April 2017

Spring Framework

Spring Framework

The Spring Framework is an open source application framework for the Java platform which aims to make J2EE development easier. Spring framework offers a lot of freedom to Java developers yet provides well-documented and easy to use solutions for common practices in the industry.

Spring is a glue framework that gives an easy way of configuring and resolving dependencies throughout the J2EE stack. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promote good programming practice by enabling a POJO-based programming model.

Goals of Spring Framework
          Reduce glue code/plumbing work
        Spring Framework takes lot of load off the programmer by providing dependencies when required and by using AOP.
          Externalize dependencies
        Dependencies are described in a separate file (xml) rather than mixing it with the business logic code itself. This gives a better control over the application.
          Manage dependencies at a single place
        Dependencies can be managed better due to this.
          Improve testability
        Actual code can easily be replaced by a stub for testing purposes.
          Foster good application design
        Since the actual implementation sits behind the interfaces, it fosters good application design.
          Flexibility
        Spring offers integration points with several other frameworks. So, you do not have to write them yourself.
        Programmers are free to choose the modules that suit their application. Spring has a well layered architecture of 7 modules:
          Spring Core
          Spring Context
          Spring AOP
          Spring DAO
          Spring ORM
          Spring WebFlow
          Spring Web MVC

Spring Framework


Features of Spring Framework

          Lightweight
        Objects in a Spring-enabled application often have no dependencies on Spring specific classes. It’s jar file is just over 2.5 MB.
        Provides support to not only J2EE applications but also to stand alone applications
          Inversion of Control (IoC) and Dependency Injection
        The core of the Spring Framework is based on the principle of IoC. Applications that follow the IoC principle use configuration that describes the dependencies between its components.
        Ioc or to be more descriptive, Dependency Injection aims to offer a simpler mechanism for providing components dependencies.
          AOP
        Aspect Oriented Programming can be used to separate cross-cutting concerns from business logic. These concerns, then can be applied to many parts of the application. Logging and security are typical examples of such concerns.
          Pojo based programming
        Spring based applications need not extend/implement any spring specific classes. It leads to a simpler yet extensible programming model.


Friday 24 February 2017

Spring - Bean

Spring - Bean Definition

The objects that form the backbone of application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled and managed by a Spring IoC container. These beans are created with the configuration metadata that we supply to the container.
The bean definition contains the information called configuration metadata which is needed for the container to know the followings:
·        How to create a bean
·        Bean's lifecycle details
·        Bean's dependencies
The above configuration metadata translates into a set of the following properties that make up the bean definition.
class
The class attribute is mandatory. The class attribute specifies the class of the bean to be constructed

id and name
Every bean has one or more ids called identifiers, or names. These ids must be unique within the BeanFactory or ApplicationContext the bean is hosted in. In an XmlBeanFactory, you use the id or name attributes to specify the bean id.

singleton or prototype
Beans are defined to be deployed in either singleton or non-singleton mode. When a bean is a singleton, only one shared instance of the bean will be managed and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned.
The non-singleton or prototype mode of a bean deployment results in the creation of a new bean instance every time a request for that specific bean is done. This is ideal for situations where for example each user needs an independent user object.

By default beans are deployed in singleton mode. By changing the type to prototype, each request for a bean will create a new bean object.
In the below example, two beans are declared of which one is defined as a singleton, and the other one is a non-singleton (prototype). 
protoBean is created each and every time a client asks the BeanFactory for this bean, while singleBean is only created once; a reference to the exact same instance is returned on each request for this bean.

Spring - Bean
constructor arguments

This is used to inject the dependencies. Beans define their dependencies only through constructor arguments, arguments to a factory method, or properties which are set on the object instance after it has been constructed.  The container then inject those dependencies when it creates the bean.
Inversion of Control/Dependency Injection exists in two major variants:
  • setter-based dependency injection is realized by calling setters on the beans after invoking a no-argument constructor or no-argument static factory method to instantiate the bean.
  • constructor-based dependency injection is realized by invoking a constructor with a number of arguments, each representing a collaborator or property.

bean properties
Bean properties and constructor arguments can be defined as either references to other managed beans or values defined inline. The XmlBeanFactory supports a number of sub-element types within its property and constructor-arg elements for this purpose.  This is used to inject the dependencies.


autowiring mode

It is possible to automatically let Spring framework resolve dependencies for the bean by inspecting contents of the BeanFactory. This is kown as Autowiring.  A BeanFactory is able to autowire relationships between collaborating beans.
The autowiring functionality has five modes. Autowiring is specified per bean and can thus be enabled for some beans, while other beans won't be autowired.
Using autowiring, it is possible to reduce or eliminate the need to specify properties or constructor arguments, saving a significant amount of typing. In an XmlBeanFactory, the autowire mode for a bean definition is specified by using the autowire attribute of the bean element.
 Autowiring modes




Monday 13 February 2017

Bean scopes

Bean scopes in Spring

When we create a bean definition, we are actually creating is actual instances of the class defined by that bean definition. You can control the various dependencies and configuration values along with the scope of the objects created from a particular bean definition. Beans can be defined to be deployed in one of a number of scopes: out of the box, the Spring Framework supports five scopes of which three are available only if you are using a web-aware ApplicationContext.


Scope
Description
singleton
A single bean definition to a single object instance per Spring IoC container.
prototype
A single bean definition to any number of object instances.
request
A single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session
A single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
global session
A single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.


The singleton scope
The singleton scope is the default scope in Spring. For a singleton bean, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.
When you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.

The prototype scope

Prototype scope of bean will create a new bean instance every time a request for that specific bean is made. You should use the prototype scope for all beans that are stateful, while the singleton scope should be used for stateless beans.
When deploying a bean in the prototype scope, please take note that , Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, decorates and otherwise assembles a prototype object, hands it to the client and then has no further knowledge of that prototype instance. This means that while initialization lifecycle callback methods will be called on all objects regardless of scope, in the case of prototypes, any configured destruction lifecycle callbacks will not be called. It is the responsibility of the client code to clean up prototype scoped objects and release any expensive resources that the prototype bean(s) are holding onto.

The request scope

The Spring container will create a brand new instance of the bean definition for each and every HTTP request. You can change the internal state of the instance that is created as much as you want. When the request is finished processing, the bean that is scoped to the request will be discarded.

The session scope

The Spring container will create a brand new instance of the  bean using the bean definition for the lifetime  of a single HTTP Session. In other words, the bean will be effectively scoped at the HTTP Session level. Just like request-scoped beans, you can change the internal state of the instance that is created. When the HTTP Session is eventually discarded, the bean that is scoped to that particular HTTP Session will also be discarded.

The global session scope

The global session scope is similar to the HTTP Session scope, and makes sense in the context of portlet-based web applications. The portlet specification defines the notion of a global Session that is shared amongst all of the various portlets that make up a single portlet web application. Beans defined at the global session scope are scoped to the lifetime of the global portlet Session.


Bean scopes
Bean scopes