Happy Diwali
happy diwali

Spring

Spring Framework
Spring Framework  :  Spring is a lightweight framework. It can be thought of as a framework of frameworks because it provides support to various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF etc. The framework, in broader sense, can be defined as a structure where we find solution of the various technical problems. The core features of the Spring Framework can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Although the Spring Framework does not impose any specific programming model, it has become popular in the Java community as an alternative to, replacement for, or even addition to the Enterprise JavaBean (EJB) model.
The Spring Framework comprises several modules that provide a range of services:

DAO & JDBC

ORM


JEE

WEB MVC Module

AOP
IOC

Advantages : There are many advantages of Spring Framework. They are as follows:
1) Lightweight: Spring framework is lightweight because of its POJO implementation. The Spring Framework doesn't force the programmer to inherit any class or implement any interface. That is why it is said non-invasive.
2) Easy to develop JavaEE application: The Dependency Injection feature of Spring Framework and it support to various frameworks makes the easy development of JavaEE application.
3) Easy to test: The Dependency Injection makes easier to test the application. The EJB or Struts application require server to run the application but Spring framework doesn't require server.
4) Loose Coupling: The Spring applications are loosely coupled because of dependency injection.
5) Powerful abstraction: It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and JTA.
6) Declarative support: It provides declarative support for caching, validation, transactions and formatting
IOC (Inversion Of Control);
For all modules IOC (Inversion Of Control) is the base Module.
IOC will take care of creating an object to the class and setting values of the attributes of the object.
IOC container mainly used for configuration. Data is supplied to the framework through xml file. Whatever we set inside xml file, will be used inside java program.
The IOC module provides configuration to the other modules of spring framework.
AOP(Aspect Oriented Programming):
It is anti Object oriented programming. Oop concepts mainly used for hierarchical (inherited) classes, the classes which are under one hierarchy. AOP is for any classes, horizontally no relation is required among the classes. After developing we the aspect we can apply that aspect horizontally to any of the classes. No relation is required among the classes.

JDBC DAO (Java Enterprise Edition and Data Access Object) module:
Used for interacting with the database using JDBC API. In order to minimize development work while interacting with the database by using JDBC, we use DAO module. DAO module internally uses pure JDBC API.
No additional features like ORM or cache Mechanisms are used. It receives just the SQL query and does all the necessary steps to send the query to the database.

ORM (Object Relational Mapping):
If we are using hibernate framework to interact with the database from a java program, then the interaction procedure is simplified by using Spring ORM. The ORM tools popularly used today are hibernate and iBatis. The ORM tools usage is simplified by the ORM module.
ORM module straightaway gives Session object by starting the Transaction to the java program.

WEB MVC (Model View Controller) module:
Almost similar to struts and JSF. Used only for developing web applications.
JEE:
Simplifying development of EJB, JMS (Java Messaging Service).

IOC Module

IoC Container The IoC container is responsible to instantiate, configure and assemble the objects. The IoC container gets informations from the XML file and works accordingly. The main tasks performed by IoC container are:

·to instantiate the application class
·to configure the object
·to assemble the dependencies between the objects
There are two types of IoC containers. They are:
1.    BeanFactory
2.    ApplicationContext
 Creating spring application in Eclipse IDE
the simple steps to create the spring application in Eclipse IDE.
·create the java project
·add spring jar files
·create the class
·create the xml file to provide the values
·create the test class
Go to File menu - New - project - Java Project.
Create Java class
app1/src/com/lara/Person.java
packagecom.lara;

publicclass Person {
            private String firstName, lastName;
           
            public Person()
            {
                        System.out.println("Person");
            }
            public String getFirstName() {
                        System.out.println("getFirstName");
                        returnfirstName;
            }

            publicvoidsetFirstName(String firstName) {
                        System.out.println("setFirstName");
                        this.firstName = firstName;
            }

            public String getLastName() {
                        System.out.println("getLastName");
                        returnlastName;
            }

            publicvoidsetLastName(String lastName) {
                        System.out.println("setLastName");
                        this.lastName = lastName;
            }
}
Create the test class
Manager.java
packagecom.lara;

publicclass Manager {
            publicstaticvoid main(String[] args) {
                        Person p1 = new Person();
                        p1.setFirstName("Ramu");
                        p1.setLastName("B");
                        System.out.println("object is ready withteh state");
                        System.out.println(p1.getFirstName());
                        System.out.println(p1.getLastName());
            }
}

Output:
Person
setFirstName
setLastName
object is ready withteh state
getFirstName
Ramu
getLastName
B
Without framework we are managing one object to bean class.
If the data is some configuration data (programmers data) use Spring framework and keep the data in the xml file under IOC.
Add spring jar files
For IOC update build path with the two relevant jar files. Right click on app1àPropertiesàJava Build PathàLibrariesàAdd External JARs: add Spring.jar and Commons-logging.jar files.
Create a xml file to store the configuration data.
Right click on srcàNewàFile: create on .xml file, Eg. beans.xml (can be any name).
Create the xml file :
beans.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<!--
  - DispatcherServlet application context for the image database.
  -->
<beansxmlns="http://www.springframework.org/schema/beans"
                        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"
                        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                                                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

            <beanid="person1"class="com.lara.Person">
                        <property name="firstName"value="Sagar"/>
                        <property name="lastName"value="B"/>
            </bean>
           
</beans>
Manager2.java
packagecom.lara;

importorg.springframework.beans.factory.BeanFactory;
importorg.springframework.beans.factory.xml.XmlBeanFactory;
importorg.springframework.core.io.ClassPathResource;

publicclass Manager2 {
            publicstaticvoid main(String[] args) {
                        BeanFactory factory = newXmlBeanFactory(newClassPathResource("beans.xml"));
                       
                        Person p1 = (Person) factory.getBean("person1");
                        System.out.println("Object is ready with the state");
                        System.out.println(p1.getFirstName());
                        System.out.println(p1.getLastName());
            }
}
Whatever is developed inside the src folder inside eclipse, the framework will place that in the bin folder.
We can add any number of bean tag in the beans.xml file.
beans.xml
<beansxmlns="http://www.springframework.org/schema/beans"
                        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"
                        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                                                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

            <beanid="person1"class="com.lara.Person">
                        <property name="firstName"value="Sagar"/>
                        <property name="lastName"value="B"/>
            </bean>
           
            <beanid="person2"class="com.lara.Person">
                        <property name="firstName"value="Shiva"/>
                        <property name="lastName"value="Boss"/>
            </bean>
           
</beans>
Manager2.java
packagecom.lara;

importorg.springframework.beans.factory.BeanFactory;
importorg.springframework.beans.factory.xml.XmlBeanFactory;
importorg.springframework.core.io.ClassPathResource;

publicclass Manager2 {
            publicstaticvoid main(String[] args) {
                        BeanFactory factory = newXmlBeanFactory(newClassPathResource("beans.xml"));
                       
            Person p1 = (Person) factory.getBean("person1");
            Person p2 = (Person) factory.getBean("person1");
            System.out.println("-------");
            Person p3 = (Person)factory.getBean("person2");
            Person p4 = (Person)factory.getBean("person2");
            System.out.println("-------");
            System.out.println("Object ready");
            System.out.println(p1.getFirstName());
            System.out.println(p1.getLastName());
            System.out.println(p2.getFirstName());
            System.out.println(p2.getLastName());
            System.out.println(p3.getFirstName());
            System.out.println(p3.getLastName());
            System.out.println(p4.getFirstName());
            System.out.println(p4.getLastName());
            }
}

Person
setFirstName
setLastName
-------
Person
setFirstName
setLastName
-------
Object ready
getFirstName
Sagar
getLastName
B
getFirstName
Sagar
getLastName
B
getFirstName
Shiva
getLastName
Boss
getFirstName
Shiva
getLastName
Boss
This shows that for each bean tag inside beans.xml file, only one object is created, the reference to it is assigned to multiple variables if we try to create more than one object.
By default the scope is singleton, we can change it by making the following changes:
<beansxmlns="http://www.springframework.org/schema/beans"
                        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"
                        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                                                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

            <beanid="person1"class="com.lara.Person"scope="prototype">
                        <property name="firstName"value="Sagar"/>
                        <property name="lastName"value="B"/>
            </bean>
           
            <beanid="person2"class="com.lara.Person">
                        <property name="firstName"value="Shiva"/>
                        <property name="lastName"value="Boss"/>
            </bean>
           
</beans>
Now if we run the same program we get two separate objects for the person1 tag as shown below.
Person
setFirstName
setLastName
Person
setFirstName
setLastName
-------
Person
setFirstName
setLastName
-------
Object is ready with the state
getFirstNam

If scope is prototype, on calling getBean() method a new person object is created.

By default the scope is singleton. We can also manually specify itexpicitly.:

<beanid="person1"class="com.lara.Person"scope="singleton">
<property name="firstName"value="Sagar"/>
<property name="lastName"value="B"/>
</bean>

If we use the property tag to specify value, framework will be looking for setFirstName method inside bean class.



Difference between BeanFactory and the ApplicationContext The org.springframework.beans.factory.BeanFactory and the org.springframework.context.ApplicationContext interfaces acts as the IoC container. The ApplicationContext interface is built on top of the BeanFactory interface. It adds some extra functionality than BeanFactory such as simple integration with Spring's AOP, message resource handling (for I18N), event propagation, application layer specific context (e.g. WebApplicationContext) for web application. So it is better to use ApplicationContext than BeanFactory.
Using BeanFactory    The XmlBeanFactory is the implementation class for the BeanFactory interface. To use the BeanFactory, we need to create the instance of XmlBeanFactory class as given below:
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);
The constructor of XmlBeanFactory class receives the Resource object so we need to pass the resource object to create the object of BeanFactory.
Using ApplicationContext
The ClassPathXmlApplicationContext class is the implementation class of ApplicationContext interface. We need to instantiate the ClassPathXmlApplicationContext class to use the ApplicationContext as given below:
ApplicationContext context =
            new ClassPathXmlApplicationContext("applicationContext.xml");
The constructor of ClassPathXmlApplicationContext class receives string, so we can pass the name of the xml file to create the instance of ApplicationContext.
There are two types of injection
·         Setter Injection
·         Constructor Injection
We are using setter injection which requires setter methods. Framework is injecting data into the object by using setter methods.

Dependency Injection in Spring  Dependency Injection (DI) is a design pattern that removes the dependency from the programming code so that it can be easy to manage and test(manager) the application. Dependency Injection makes our programming code loosely coupled. To understand the DI better, Let's understand the Dependency Lookup (DL) first:
The Dependency Lookup is an approach where we get the resource after demand. There can be various ways to get the resource for example:
A obj = new AImpl();
In such way, we get the resource(instance of A class) directly by new keyword. Another way is factory method:
A obj = A.getA();
This way, we get the resource (instance of A class) by calling the static factory method getA().
Alternatively, we can get the resource by JNDI (Java Naming Directory Interface) as:
Context ctx = new InitialContext();
Context environmentCtx = (Context) ctx.lookup("java:comp/env");
A obj = (A)environmentCtx.lookup("A");
There can be various ways to get the resource to obtain the resource. Let's see the problem in this approach.
Problems of Dependency Lookup
There are mainly two problems of dependency lookup.
tight coupling The dependency lookup approach makes the code tightly coupled. If resource is changed, we need to perform a lot of modification in the code.
Not easy for testing This approach creates a lot of problems while testing the application especially in black box testing.

No comments:

Post a Comment

happy diwali
happy diwali