Sunday, August 25, 2013

Spring Basic

Spring Basic

Spring is a lightweight framework.
Also can describe as a framework of frameworks because it provides support to various frameworks such Struts, Hibernate, EJB, etc.

The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM, WEB MVC etc.


IOC (Inversion of Control) and Dependency Injection

* These are the design patterns which used to remove the dependency from the program code. In other sense IOC makes the code as loosely coupled.
* In such a case it easier to modify the logic in one area and inject them to all areas without modifying the whole project.
* Extremely powerful Inversion of control(IoC) framework to help decouple your project components’ dependencies.

In Spring framework, IOC container is responsible to inject the dependency.

Provide metadata to the IOC container - ( * by XML file / * by annotation ).

Advantages of dependency Injection -
* makes the code loosely coupled and easy to maintain
* makes the code easy to test.

Why Spring is lightweight ?
Because of its POJO implementation. The Spring framework doesn't force to programmer to inherit any class or implement any interface. That is why it is said non-invasive.


Spring Modules -

Framework is comprise of many modules.
Core, beans, context, expression language, AOP, Aspects, Instrumentation, JDBC, ORM, OXM, JMS, Transaction, Web, Servlet, Struts, etc ..

These are grouped as follows;
* Data Access / Integration : JDBC, ORM, OXM, JMS, Transaction
* WEB ( MVC / Remoting ) : Web, Servlet, Portlet, Struts
* Spring Core Container : Core, beans, context, Expression Language
* AOP
* Aspects
* Instrumentation
* Test
TestThis layer provides support of testing with Junit and TestNG.

Spring Core Container – This contains core, beans, context and Expression Language (EL) modules.

Core and Beans – This module provide IOC and Dependency Injection features.

Context – This module supports initialization (I18N), EJB, JMS, Basic Remorting.

Expression Language – It is an extension to the EL defined in JSP. Supports to getting and setting property values, method invocation, accessing collections and indexes, named variables, logical and arithmetic operators, retrieval by object names, etc.

AOP, Aspects and Instrumentation – This modules support aspect oriented programming implementation where you can use Advices, Point-cuts etc. to decouple the code.

The Aspects module provides support to integration with AspectJ.

The instrumentation module provides support to class instrumentation and class loader implementations.

Data Access / Integration – The group comprise of JDBC, ORM, OXM, JMS, and Transaction modules. (interact with the Database)

Web – This is support to create web application.

IoC (Inversion of Control) Container

* IoC container is responsible to instantiate, configure and assemble the objects.
This container gets the information from the XML and work accordingly.

Main tasks of IoC :
      1. to instantiate the application class
      2. to configure the object
      3. to assemble the dependencies between the objects

Two types of IoC containers
      1. BeanFactory
      2. ApplicationContext

Difference between BeanFactory and ApplicationContext -

Those are acts IoC containers. The ApplicationContext interface is builf on top of the BeanFactory Interface. It is add some extra functionality than the BeanFactory. Those are;
    • simple integration with Sping's AOP
    • message resource handling ( for I18N )
    • event propagation
    • application layer specific context ( e.g. WebApplicationContext ) for Web application

Using BeanFactory -

The XMLBeanFactory is the implementation class for the BeanFactory interface.

Resource resource = new ClassPathResource("ApplicationContext.xml");
BeanFactory beanFactory = new XmlBeanFactory(resource);

Using ApplicationContext -

The ClassPathXMLApplicationContext class is the implementation class of the ApplicationContext interface.

ApplicationContext context = new ApplicationContext("ApplicationContext.xml");


Dependency Injection

Dependency Injection is a design patter that remove the dependency from the programming code.
So that it can be easy to manage and test the application.
This makes our programming code loosely coupled.

Dependency Lookup -
The dependency lookup is an approach where we get the resource after demand. There are varies ways to get the resource.
Ex -
      1. A objA = A.getA(); [ get the resource by calling the static factory method getA() ]
      2. get the resource by JNDI

Problems with Dependency Lookup -
      1. tight coupling – dependecy lookup approach makes the code tightly coupled, hence change a single resource we need to perform a lot of modification in the code
      2. Not easy for testing ( especially on Black box testing )


Dependency Injection by Constructor

We can inject the dependency by constructor. The <constructor-arg> the sub-element of <bean> is used for constructor injection.
Can inject :
      1. primitive and String-based values
      2. Dependent object ( contained object )
      3. Collection value etc.

Constructor Injection with Dependent Object

If there is HAS-A relationship between the classes, first we create the instance of dependent object and then pass it as an argument of the main class constructor.
e.g. Employee HAS-A Address, so Address class object will be the dependent.
<bean id="addressBean" class="Address">
<constructor-arg value="126B, Pubudu Uyana"></constructor-arg>
<constructor-arg value="Piliyandala"></constructor-arg>
<constructor-arg value="Western Province"></constructor-arg>
<constructor-arg value="Sri Lanka"></constructor-arg>
</bean>
<bean id="employeeBean" class="Employee">
<constructor-arg type="int" value="100123"></constructor-arg>
<constructor-arg value="Sanjeeva"></constructor-arg>
<constructor-arg value="Pathirana"></constructor-arg>
<constructor-arg><ref bean="addressBean"/> </constructor-arg>
</bean>

Constructor Injection with collections

Can inject collection values by constructor in Spring framework.
Can use with <constructor-arg>

1. list ( use list, set )

<constructor-arg>
<list>
<value>94773020595</value>
<value>94773020596</value>
<value>94112613044</value>
</list>
</constructor-arg>
<constructor-arg>
<list>
<ref bean="books1Bean"/>
<ref bean="books2Bean"/>
<ref bean="books3Bean"/>
<ref bean="books4Bean"/>
</list>
</constructor-arg>

2. map

<constructor-arg>
<map>
<entry key="Sports Journal" value="TENs sport"></entry>
<entry key="Science" value="Gravity"></entry>
</map>
</constructor-arg>
<constructor-arg>
<map>
<entry key-ref="newsPaper1Bean" value-ref="editor1Bean"></entry>
<entry key-ref="newsPaper2Bean" value-ref="editor2Bean"></entry>
</map>
</constructor-arg>


Inheriting Bean in Spring

By using the parent attribute of bean, we can specify the inheritance relation between the beans.
Such case parent bean values will be inherited to the current bean.


Dependency Injection By Setter method

Can inject the dependency by setter method also.
The <property> sub-element of <bean> is used for setter injection.

<bean id="studentBean" class="com.Student">
<property name="studentRef"><value>STD001</value></property>
<property name="fName"><value>Sanjeeva</value></property>
<property name="lName"><value>Pathirana</value></property>
<property name="age"><value>30</value></property>
</bean>

Setter Injection with Dependent object

For this injection we can use for HAS-A relationship occurrences.
E.g. Student HAS-A Academic Year
<bean id="studentBean" class="com.Student">
...
<property name="academicInfo" ref="academicInfoBean"></property>
</bean>

<bean id="academicInfoBean" class="com.AcademicInfo">
...
</bean>

Setter Injection with Collection Example

Can inject collection values by using setter method.
There are 3 elements which use with <property> element.

1. list

<property name="extraCurriculums">
<list>
<value>Annual Debt</value>
<value>Rugby Tournament</value>
<value>Poem competition</value>
</list>
</property>


<bean id="grade1Bean" class="com.Grade">
<property name="gradeLevel"><value>1st Class</value></property>
<property name="gradeDescription"><value>Over 3.5 GPA</value></property>
</bean>

<list>
<ref bean="grade1Bean"/>
<ref bean="grade2Bean"/>
</list>

2. map

<property name="semesterInfoMap">
<map>
<entry key="1st Semester - Starts" value="Jan 2014"></entry>
</map>
</property>

<property name="subjectInfoMap">
<map>
<entry key-ref="subject1Bean" value-ref="lecturer1Bean"></entry>
</map>
</property>

Few Points about setter injection

1. Setter injection overrides constructor injection. If we use both IoC container use the setter injection.
2. We can easily change the value by setter injection. It doesn't create a new bean instance always like constructor injection. So setter injection is more flexible than the constructor injection.