Saturday, August 12, 2017

Beans

Beans

  • simple, reusable module components
  • complete entities to themselves and the IoC container will resolve any dependencies they may need

Bean Creation

coding POJO
adding a bean configuration element to the Spring XML configuration file or annotating the POJO,


Thursday, January 7, 2016

IoC - Inversion of Control

Main idea of Inversion of Control concept :


  • component dependencies
  • lifecycle events
and
  • configuration

reside outside of the component itself (In Spring : In the Framework).



Though it is like giving up too much control,  it can make your code :

  • more manageable
  • more testable
  • more portable

Best practice patterns of IoC Framework :


  • Aspects of Spring IoC    -     resemble and include Factory and Observer pattens
  • Implementation of the Framework    -    Dependency Injection pattern


Spring IoC Container 



  • Core of Spring Framework.
  • Spring's IoC container manages the objects (beans) that it is configured to instantiate through its factory, from instantiation to destruction, manages a bean's scope, lifecycle events, and any AOP features for which it has been configured and coded.
  • Spring's management of the container objects adds flexibility and control to your application, and provides a central place of configuration management for your POJOs. 
  • For example, through Spring IoC you can configure the number of instances of the component, whether the component is a singleton or not, and at what point the component is created and destroyed in memory. 
  • In Spring, the initialization of a bean by the framework is exactly equivalent to using the new keyword to instantiate an object in Java code. Once the framework has instantiated the object, it manages the scope of the bean, based on its configuration. 
  • Because the IoC container is managing the beans, JNDI lookups that are typical in Java EE containers are no longer required, leaving your code container-agnostic and easier to unit test both inside and outside of the framework. And while you are coding to interfaces as part of good OO practice, 
  • Spring allows you to manage what implementations are used by leveraging dependency injection, resulting in cleaner, decoupled components. 
  • The IoC container can also be configured to receive instantiation and destruction callback events for a particular bean. Certain components such as a database connection pool obviously need to be initialized and destroyed when the application is shutdown. Instead of using your custom code, Spring can manage these lifecycle events.
  • The IoC container enforces the dependency injection pattern for your components, leaving them loosely coupled and allowing you to code to abstractions. 







The Java Naming and Directory InterfaceTM (JNDI) is an application programming interface (API) that provides naming and directory functionality to applications written using the JavaTM programming language. It is defined to be independent of any specific directory service implementation.




s inform Spring through an XML configuration file that the recorder bean is implemented by the LocalVoteRecorder class :-

<bean id="recorder" class="com.vij.nondip.LocalVoteRecorder" />

map the recorder bean to the VotingBooth bean by setter injection in that beans definition :-

<bean id="votingBooth" class="com.vij.nondip.VotingBooth">
         <property name="voteRecorder" ref="recorder" />
</bean>

with this configuration and the Spring framework, and through dependency injection, we have finally removed the low-level component dependencies and have achieved true dependency inversion



Dependency Injection

DIP - Dependency Inversion Principle


1994 , Robert C. Martin

RFI problem


According to Martin, Inter-dependency causes coding problems :
  • Rigidity       :  hard to change because every change affects too many other parts of the system
  • Fragility      :  When you make a change, unexpected parts of the system break
  • Immobility  :  hard to reuse in another application because it cannot be disentangled from the current application


DIP rules to fix RFI


  • High level modules (which contain your business logic and all of the important meat of your application) should not depend upon low level modules, both should depend upon abstractions. 

The reason for this is if these lower level components were to change, 
the changes might affect the higher level components as well.

  • Abstractions should not depend upon details, details should depend upon abstractions. 

The interface or abstract class 
should find the common behaviors in the code and work backwards.
should cater to the intersection between the needs of your business logic 
and the common behaviors of the lower level modules.
should also leave the details of how these behaviors are implemented to the implementation classes.



non-DIP compliant program

VotingBooth class is directly dependent on VoteRecorder, which has no abstractions and is the implementing class.



DIP Dependency Inverted Version









Now the LocalVoteRecorder class, the implementing class of the VoteRecorder interface, is completely decoupled from the VotingBooth class.
We have removed all hard-coded references to lower level classes.
According to the rules of DIP, this is all we need to do in order to rid our code of RFI.
However, there is one problem with this implementation.
We don’t have a main method.
We definitely need one in order to run our application, and somewhere in this main method we will need to instantiate the LocalVoteRecorder.
By instantiating the LocalVoteRecorder in our main method, we would break Rule #1 of Dependency Inversion.
We have coded to the abstraction, we have integrated our changes, but our application would still have a dependency on a lower level class. 



DI - Dependency Injection

Dependency Injection takes the level of decoupling that began with the Dependency Inversion Principle one step further. 
Dependency injection has the concept of an assembler 4, or what in Java is commonly referred to as a Factory, that instantiates the objects required by an application and “injects” them into their dependent objects. 
In the case of a dependency injection-informed framework such as Spring, components are coded to interfaces, just as in the DIP example above. 
But now the IoC container manages the instantiation, management, and class casting of the implemented objects so that the application doesn't have to. 
This removes any true dependencies on low-level implemented classes.

Spring uses the concept of a BeanFactory as its assembler, and it is the BeanFactory that manages the JavaBeans you have configured to run within it. 
In the next section we will discuss Spring's IoC container and how it makes use of dependency injection patterns to make your code, well, RFI-free, and just better.

Types of Dependency Injection


  • Constructor Injection
                           The constructor arguments are injected during instance instantiation.
  • Setter Injection
                           Dependencies are “set” in the objects through setter methods defined in a Spring                                  configuration file.
  • Interface Injection
                           It’s a different type of DI that involves mapping items to inject to specific interfaces.



Inversion of Control





What makes Framework work?

A framework is essentially a skeleton, a structure around which the fleshing out of your application occurs. 

Frameworks tend to be built around a design pattern and consist of frozen spots – structural components which are unmodified by the developer -- and hot spots, the pieces that an application developer contributes. 

In Spring, the hot spots are developer-contributed POJOs which are configured to run within the framework.

*POJO - Plain Old Java Object

Wednesday, January 6, 2016

History of Spring

Spring framework was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.



In its early days, Spring was created as an alternative to heavier enterprise Java technologies, especially EJB. Spring offered a lighter and leaner programming model as compared to EJB. It empowered plain old Java objects (POJOs) with powers previously only available using EJB and other enterprise Java specifications. Over time, EJB and the Java 2 Enterprise Edition (J2EE) evolved. EJB started offering a simple POJO-oriented programming model of its own. Now EJB employs ideas such as dependency injection (DI) and aspect-oriented programming (AOP), arguably inspired by the success of Spring.

Although J2EE (now known as JEE) was able to catch up with Spring, Spring never stopped moving forward. Spring has continued to progress in areas where, even now, JEE is just starting to explore or isn’t innovating at all. Mobile development, social API integration, NoSQL databases, cloud computing, and big data are just a few areas where Spring has been and is innovating. And the future continues to look bright for Spring.


Tuesday, January 5, 2016

Spring in Brief


What is Spring

The most popular application development framework for enterprise Java


What is Spring Framework

An open source java platform.
Framework of Frameworks: supports other frameworks like hibernate
It has modules: IoC, AOP

Advantages of Spring

Predefined Templates – for JDBC, JPA ; save a lot of code
Lightweight – no inherit or implement of class, POJO implementation
Loosely Coupling – dependency injection
Easy to Test – dependency injection
Fast Development – dependency injection
Powerful Abstraction
Declarative Support – for validation, formatting

Dependency Injection

Dependency  :
          object A depends on object B, if object A needs object B to execute  correctly.


Tightly Coupled 

If object B has other dependencies, A need to know about them too.
If change of implementation, need to change the code.
         Loosely Coupled 
       ●Reusable of code
       ●Easy to test



Injection :
       adding something external to the flow.
         ●Glue 2 classes together while keeping them independent.

Two types of Dependency Injection in Spring
Constructor based
Setter based


Inversion of Control (IoC)

A design pattern, removes dependency from code, makes the code loosely coupled.
No modification of code if logic is moved to a new environment.

Spring IoC Container


In Spring Framework, IOC container is responsible to inject the dependency.
Provide metadata to the IOC container either by XML file or annotation.
Two types of IoC Containers in Spring
BeanFactory
ApplicationContext


What is a Bean


The objects that are instantiated, assembled or managed by the Spring IOC container.
Created with configuration metadata supplied to the container in the form of XML.
declare bean using <bean> element and inject <bean> with using
 <constructor-arg> and <property> elements in xml configuration file.

Another way of bean configuration is using annotations.


Spring as a Container


● Spring is a Container of Beans/a Factory of Beans, dependency injection is possible.


● What is a container?

● Tomcat Servlet Container
● All servlets are configured in xml and supply the classes.
● Tomcat creates servlets required by reading xml

         ● Similarly;
         ●  Spring is a container of beans, POJOs (objects) are contained in spring       
           container, supplied as requested by others.
         ●  All objects are managed by Spring Container
          ● Handles the instantiation
          ● Handles whole lifecycle
          ● Handles destruction of objects

Bean Factory

● Factory Pattern
●   Instead of creating a new object, make a call to Object Factory which creates new objects according to some configuration and hands it over to the requested object.
● ApplicationContext
●   BeanFactory with additional functionalities.
●   When defining ApplicationContext, reads Spring XML and initializes available beans itself without any call of getBean
●   When another object call getBeanApplicationContext handsover the objects that already been initialized.
● Advantage
● Spring bean is created in the Bean Factory
● Spring has the handle of the Bean
● Spring acts as a container of this newly created bean


Bean Life Cycle


●   Spring container is responsible for managing the lifecycle of beans created through it.
●   When a bean is instantiated, it may be required to perform some initialization to get it into a usable state.
●   Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required.


●   Lifecycle consists of call back methods :
             1. post initialization call back methods
             2. pre destruction call back methods  
●  Spring Framework provides 4 ways of controlling lifecycle events of bean :

            1. InitializingBean and DisposableBean callback interfaces
            2. custom init() and destroy() methods in bean configuration file
            3. @PostConstruct and @PreDestroy annotations
            4. Other Aware interfaces for specific behavior




InitializingBean and DisposableBean callback interfaces with single methods in each



org.springframework.beans.factory

InitializingBean : void afterPropertiesSet() throws Exception;

                                   allows a bean to perform initialization work after all necessary                                                  properties on the bean have been set by the container. 
DisposableBean : void distroy() throws Exception;

                                   allows a bean to get a callback when the container containing it is                                          destroyed. 


custom init() and destroy() methods in bean configuration file

The previous one is not a preferable way to initialize the bean because it tightly couple your bean class with spring container.
better approach is to use “init-method” attribute in bean definition in applicationContext.xml file.
The default init and destroy methods in bean configuration file can be defined in two ways:

Bean local definition applicable to a single bean

<beans>
  <bean id="beanC" class="com.virtusa.model.BeanCinit-method="customInitdestroy-method="customDestroy"/>
</beans>
Global definition applicable to all beans defined in beans context
<beans default-init-method="customInitdefault-destroy-method="customDestroy">
  <bean id="beanAclass="com.virtusa.model.BeanA“/>
  <bean id="beanBclass="com.virtusa.model.BeanB“/>
</beans>


@PostConstruct and @PreDestroy annotations


Spring 2.5 onwards, you can use annotations also for specifying life cycle methods using @PostConstruct and @PreDestroy annotations.

@PostConstruct annotated method
  will be invoked after the bean has been constructed
  using default constructor and just before it’s instance
  is returned to requesting object.

@PreDestroy annotated method
  is called just before the bean is about be destroyed
  inside bean container.

this post processor will do the validation at the back end :
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />


Other aware interfaces for specific behavior

Spring offers a range of Aware interfaces that allow beans to indicate to the container that they require a certain infrastructure dependency. Each interface will require you to implement a method to inject the dependency in bean.

● These interfaces can be summarized as :

ApplicationContextAware
ApplicationEventPublisherAware
BeanClassLoaderAware
BeanFactoryAware
BeanNameAware
BootstrapContextAware
LoadTimeWeaverAware
MessageSourceAware
NotificationPublisherAware
PortletConfigAware
PortletContextAware
ResourceLoaderAware
ServletConfigAware
ServletContextAware


Bean Scope

2 basic bean scopes : 

● Singleton – only once per Spring container
●    when ApplicationContext initialized, all Singleton beans are initialized.
● Prototype – new bean created with every request or reference
●   spring waits for a getBean to happen, then it initializes the prototype, a new reference.
●  ex: Point0 , defined as a prototype bean, if it is referenced in two other beans, each of those beans would have different instance of that Point0 object.

other bean scopes :

Web-aware scopes
        Spring tights to web applications, can use to create servlet beans, tights to servlet API. Spring knows when is a new request, when is a new session. Can tie the beans scope to request and the session.

● Request - new bean per servlet request
●    call getBean inside a new request scope, a new bean is created, but in same request scope, same bean is going to be used.
● Session - new bean per session
●   if one user access a single session, no matter how many getBean calls happen, only one bean is returned, if one user with new session, a new bean is created.
● Global Session - new bean per global HTTP session (portlet context)
●   if have a global session and an individual portlet sessions, can tie a bean into a portlet context.

Bean Auto-wiring in Spring 

●   This feature of spring framework enables injecting object dependency implicitly.
●   Work with reference only, cannot use to inject primitive or string values.
● The Spring Container can autowire relationships between collaborating beans without using  <constructor-arg> and <property> elements which used to skip some of the configurations.
●   First look for bean type to be injected or if there are multiple beans of same type then looking for a matching name or a clue.

●   Auto-Wiring modes
● no  : no autowiring by default (autowiring is OFF) ;
       explicitely set the dependencies using tags in bean definitions
● byName  : inject the object dependency based on bean name, property name = bean name  ; internally calls setter
● byType  : inject the object dependency based on bean type,
     property name != bean name  ; internally calls setter
● byConstructor  : injects the dependency by calling the constructor of the class,
     (constructor with larger no of parameters)
● Autodetect  : Spring first tries to wire using autowire by constructor,
      if it does not work, Spring tries to autowire by byType.


Annotations

Used to provide bean configuration , configure the dependency injection
@Required
applies to bean property setter methods.
@Autowired
can apply to bean property setter methods, non-setter methods, constructor and properties.
@Qualifier
along with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired.
JSR-250 Annotations
Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations.

Post processor

Post Processor


Spring MVC



Aspect Oriented Programming (AOP)  

Breaking down the program logic into distinct parts, concerns.
  cross-cutting concerns : functions that span multiple points of an application.

Remove these common functionalities and create an Aspect.

  aspect : the unit of modularity (class or object : OOP)



examples of aspects : logging, caching, auditing, security
DI helps decouple your application objects from each other.
AOP helps decouple cross-cutting concerns from the objects that they affect.
AOP implementations : Spring AOP, AspectJ, JBoss AOP


AOP Concepts and Terminology 


Aspect  : A module which has a set of APIs providing cross-cutting requirements.
Join Point  : This represents a point in your application where you can plug-in AOP aspect. 
Advice  : The actual action to be taken by the aspect either before or after the method execution. 
Before Advice  : Run advice before the a method execution.
After Returning Advice  : Run advice after the a method execution regardless of its outcome.
After Throwing Advice  : Run advice after the a method execution only if method completes successfully.
After (finally) Advice  : Run advice after the a method execution only if method exits by throwing an exception.
Around Advice   : Run advice before and after the advised method is invoked.
Pointcut  : A set of one or more join points where an advice should be executed.
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. (advised     object)
Intercepter  : An aspect that contains only one advice.
AOP Proxy  : Used to implement aspect contracts, created by AOP framework. It will be a JDK dynamic     proxy or CGLIB proxy in spring framework.
Weaving  : 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.

Spring AOP



Spring AspectJ AOP implementation 

1) By annotation
@Aspect  declares the class as aspect.
@Pointcut  declares the pointcut expression.
To define advice :-
@Before  declares the before advice. It is applied before calling the actual method.
@After  declares the after advice. It is applied after calling the actual method and before returning result.
@AfterReturning  declares the after returning advice. It is applied after calling the actual method and before returning   result. But you can get the result value in the advice.
@Around  declares the around advice. It is applied before and after calling the actual method.
@AfterThrowing  declares the throws advice. It is applied if actual method throws exception.


2) By XML configuration (schema based)
To define advice :-
aop:before  applied before calling the actual business logic method.
aop: after  applied after calling the actual business logic method.
aop:after-returning  applied after calling the actual business logic method. It can be used to intercept the return value in advice.
aop:around  applied before and after calling the actual business logic method.
aop:after-throwing  applied if actual business logic method throws exception.



******************************************************************************************