Introduction:
Spring is modular and has been divided logically into independent packages, which can function independently. The architects of an application have the flexibility to implement just a few spring packages and leave out most of the packages in spring. The "Spring Framework" would not feel bad with this attitude and on the contrary encourages users to introduce spring into existing applications in a phased manner.
The "Struts" framework is no doubt a good framework to enhance the ability of the web tier, but the biggest drawback is the fact that it caters only to the web tier and leaves most of the Enterprise tier or middle tier to the fancy of the application architects. The Application architects need to provide an additional framework to deal with the enterprise tier and make sure that the new framework integrates well with the Struts framework. Spring tries to alleviate this problem by providing a comprehensive framework, which includes an MVC framework, an AOP integration framework, a JDBC integration framework, and an EJB integration framework. It also provides integration modules for major O/R mapping tools like Hibernate and JDO. Spring provides all these in a modular fashion without imposing any layer on to the user. Spring is not a take-it-or- leave-it kind of framework. It tries to seamlessly blend into the existing framework users have without hindrances. Spring also provides transaction management support using Java classes, email support packages using framework classes, web services support through proxies and many more features like the above. As mentioned earlier all these packages are optional and spring does not make any of them mandatory. Spring can seamlessly integrate with existing applications and provide specific functionality that you intend to provide with minimal demands for customization. A user can continue to use Struts for the web tier and toplink O/R for the database and meanwhile hook spring to provide e-mail services and web services support. Spring is based on the Inversion of Control/Dependency Injection pattern that has been making rounds in message boards all over the Internet.
Inversion of Control (IOC)/Dependency Injection:
Dependency Injection proposes separating the implementation of an object and the construction of objects that depend on them. The job of coordinating the implementation and construction is left to the Assembler code. The object that needs to be implemented does not need to instantiate the dependent objects and can rely on the assembler to do the job. The assembler will gather and instantiate, if necessary, the entire dependent objects and make them available to the implemented object. Since the assembler does not depend on the code directly changes can be made to the assembler without any changes to the code. The assembler gathers the required classes through configuration files so a change in the assembler only needs changes to the configuration file. In this case the Assembler code would be the spring framework.
Since the classes are independent and are integrated through the assembler, independent testing of each class can be done without affecting other application codes.
There are three types of Dependency Injections.
• Type 1 IOC also called Interface Injection & done though an interface. The interface will define the injection method and the implementation class has to implement this interface and provide concrete implementation for the injection method.
• Type 2 IOC also called Setter Injection & done via a setter method. Type 2 IOC uses setter methods to get the dependent classes it needs.
• Type 3 IOC also called Constructor Injection & it defines a constructor to get all its dependents. The dependent classes are defined in the constructor arguments
How does Spring Work?
The idea is that beans follow the Dependency Injection pattern. Beans have information on the classes dependent on them. Beans define their own attributes within bean descriptors and also define the beans they depend on in the same descriptors. The Bean does not need to locate and instantiate these classes using service locators or JNDI calls. The Assembler (Spring Framework in this case) takes care of finding these classes based on the information provided in the descriptor and makes them available to the calling class. The service locator pattern does almost the same job, so why do we need another pattern to do it. The class that needs the dependent classes needs to tell the Service Locator as to which classes are required by it and moreover the responsibility of finding these classes and invoking them falls on the calling class. This makes the classes tightly coupled with each other making them difficult to unit test them separately. In the case of the Dependency Injection pattern the responsibility is shifted to the Assembler to load these classes. The assembler can make changes to the dependent classes by simply modifying the descriptor file.
Beans, BeanFactory and Application Context
The basic package in the spring framework is the org.springframework.beans package. Spring framework uses JavaBeans and this package provides most of the basic functionality to manipulate Java beans and provides the basic infrastructure for the other spring framework classes. This package also provides the basis for the "Dependency injection" pattern that spring is based on.
There are two ways in which clients can use the functionality of the Spring Framework--the BeanFactory and the ApplicationContext. The BeanFactory is a generic factory, which stores the information about all the Spring Beans and allows the user to instantiate beans and manage them. The BeanFactory provides programmers with the facilities to implement the basic features of the Spring Framework. The ApplicationContext builds on top of the BeanFactory and inherits all the basic features of the Spring Framework. Apart from the basic features, ApplicationContext provides additional features like Event management, internationalization support and resource management.
The BeanFactory is particularly useful in low memory situations like in an Applet where having the whole API would be overkill. It provides the basic spring framework features and does not bring all the excess baggage that ApplicationContext has. ApplicationContext helps the user to use spring in a framework oriented way while the BeanFactory offers a programmatic approach
Two way to configure Spring IOC container
a) xml file: Developer can define the bean configuration in xml file and then instruct the Spring to use the xml file to configure the beans. The xml file configuration method is targeted to infrastructure providers.
b) Annotation: The @configuration spring annotation can also be used to configure the Spring IOC container. Here programmer add the @configuration to the Java class and this class is considered as special configuration class. The @configuration annotation method is targeted the developers. This is pure-java approach to configure the Spring IoC Container. The @Bean tag is used to define the bean, and the Spring framework executes the method and then register the object returned. By default the name of the method is used as the bean name.
Procedure to run spring in Eclipse:
Step 1:
Now we will create a new project in Eclipse IDE and then add the library files.
Click next. Give any name to the project, say "Spring3" and then click on the "Finish" button.
Eclipse will create a new project.
Step 2:
Create a new folder "lib" in the project space to hold the Spring 3.0 libraries. Right click on the "Spring3" in the project explorer and then select new folder option as shown below:
Then in the next screen enter "lib" next to the "Folder name" text field and click on the "Finish" button.
Step 3:
Now we will add the Spring 3. libraries to the project. Extract the "spring-framework-3.0.0.RELEASE-with-docs.zip" file if you have not extracted. Now go to the "dist" directory of the and then copy all the jar files (Ctrl+C) and paste on the lib directory (of our project) in the Eclipse IDE.
Then find the commons-logging.jar from extracted folder and also copy this file into Eclipse IDE. You will find this library into spring-framework-3.0.0.RELEASE-with-docs\spring-framework-3.0.0.RELEASE\projects\spring-build\lib\ivy folder.
Step 4:
Now all all the libraries to "Java Build Path". Right click on the "Spring3" in project explorer and then select properties. Then select "Java Build Path" --> Libraries and then click on the "Add JARs" button. And add all the libraries to Java Build Path.
Then click on the "OK" button. This will add all the libraries to the project. Now we can proceed with our Spring 3 Hello World example.
Step 5:
Create a new package net.roseindia to hold the java files. Right click on the "Spring3" and then select New --> Package. Then provide the package name as net.roseindia and click on the "Finish" button.
Step 6:
Create a new Java file Spring3HelloWorld.java under the package net.roseindia and add the following code:
package net.roseindia;
public class Spring3HelloWorld {
public void sayHello(){
System.out.println("Hello Spring 3.0");
}
}
In the above class we have created a method sayHello() which prints the "Hello Spring 3.0" on the console. In this section we will use the Spring framework to manage the Spring3HelloWorld bean, and then get the bean from the Spring runtime environment (Spring context) and the call the sayHello() method. In the next step we will xml file which will be used as Metadata to configure the bean.
Step 7:
Now create a new xml (SpringHelloWorld.xml) file using Eclipse IDE.
Add the following code to the xml file:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
class="net.roseindia.Spring3HelloWorld" />
The above xml file declares the spring bean "Spring3HelloWorldBean" of the class net.roseindia.Spring3HelloWorld. The tag is used to declare a bean in the xml file. Spring uses the xml file to configure the spring run-time environment. Spring framework manages the beans in our program. In the next sections we will learn Spring core components in detail. Note: You should move the SpringHelloWorld.xml file into src directory of the project. Jut use mouse to drag and dop in the src folder.
Step 8:
Now create a java file (Spring3HelloWorldTest.java) into net.roseindia package and add the following code:
package net.roseindia;
import java.util.Map;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.Assert;
public class Spring3HelloWorldTest {
public static void main(String[] args) {
XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
"SpringHelloWorld.xml"));
Spring3HelloWorld myBean = (Spring3HelloWorld) beanFactory
.getBean("Spring3HelloWorldBean");
myBean.sayHello();
}
}
In the above code we have created the instance of XmlBeanFactory and the retrieved the "Spring3HelloWorldBean". Then we can call the sayHello() method on the bean. The XmlBeanFactory class is extension of DefaultListableBeanFactory that reads bean definitions from an XML document. In our case it reads the bean definitions from SpringHelloWorld.xml file.
Step 9:
To run the code in Eclipse open Spring3HelloWorldTest.java in the editor and then right click and select Run as --> Java Application. This execute the Spring3HelloWorldTest.java file and following output will be displayed in the console.
Features of Spring Framework:
• Transaction Management: Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments.
• JDBC Exception Handling: The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy
• Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS.
• AOP Framework: Spring is best AOP framework
• MVC Framework: Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.
Spring is modular and has been divided logically into independent packages, which can function independently. The architects of an application have the flexibility to implement just a few spring packages and leave out most of the packages in spring. The "Spring Framework" would not feel bad with this attitude and on the contrary encourages users to introduce spring into existing applications in a phased manner.
The "Struts" framework is no doubt a good framework to enhance the ability of the web tier, but the biggest drawback is the fact that it caters only to the web tier and leaves most of the Enterprise tier or middle tier to the fancy of the application architects. The Application architects need to provide an additional framework to deal with the enterprise tier and make sure that the new framework integrates well with the Struts framework. Spring tries to alleviate this problem by providing a comprehensive framework, which includes an MVC framework, an AOP integration framework, a JDBC integration framework, and an EJB integration framework. It also provides integration modules for major O/R mapping tools like Hibernate and JDO. Spring provides all these in a modular fashion without imposing any layer on to the user. Spring is not a take-it-or- leave-it kind of framework. It tries to seamlessly blend into the existing framework users have without hindrances. Spring also provides transaction management support using Java classes, email support packages using framework classes, web services support through proxies and many more features like the above. As mentioned earlier all these packages are optional and spring does not make any of them mandatory. Spring can seamlessly integrate with existing applications and provide specific functionality that you intend to provide with minimal demands for customization. A user can continue to use Struts for the web tier and toplink O/R for the database and meanwhile hook spring to provide e-mail services and web services support. Spring is based on the Inversion of Control/Dependency Injection pattern that has been making rounds in message boards all over the Internet.
Inversion of Control (IOC)/Dependency Injection:
Dependency Injection proposes separating the implementation of an object and the construction of objects that depend on them. The job of coordinating the implementation and construction is left to the Assembler code. The object that needs to be implemented does not need to instantiate the dependent objects and can rely on the assembler to do the job. The assembler will gather and instantiate, if necessary, the entire dependent objects and make them available to the implemented object. Since the assembler does not depend on the code directly changes can be made to the assembler without any changes to the code. The assembler gathers the required classes through configuration files so a change in the assembler only needs changes to the configuration file. In this case the Assembler code would be the spring framework.
Since the classes are independent and are integrated through the assembler, independent testing of each class can be done without affecting other application codes.
There are three types of Dependency Injections.
• Type 1 IOC also called Interface Injection & done though an interface. The interface will define the injection method and the implementation class has to implement this interface and provide concrete implementation for the injection method.
• Type 2 IOC also called Setter Injection & done via a setter method. Type 2 IOC uses setter methods to get the dependent classes it needs.
• Type 3 IOC also called Constructor Injection & it defines a constructor to get all its dependents. The dependent classes are defined in the constructor arguments
How does Spring Work?
The idea is that beans follow the Dependency Injection pattern. Beans have information on the classes dependent on them. Beans define their own attributes within bean descriptors and also define the beans they depend on in the same descriptors. The Bean does not need to locate and instantiate these classes using service locators or JNDI calls. The Assembler (Spring Framework in this case) takes care of finding these classes based on the information provided in the descriptor and makes them available to the calling class. The service locator pattern does almost the same job, so why do we need another pattern to do it. The class that needs the dependent classes needs to tell the Service Locator as to which classes are required by it and moreover the responsibility of finding these classes and invoking them falls on the calling class. This makes the classes tightly coupled with each other making them difficult to unit test them separately. In the case of the Dependency Injection pattern the responsibility is shifted to the Assembler to load these classes. The assembler can make changes to the dependent classes by simply modifying the descriptor file.
Beans, BeanFactory and Application Context
The basic package in the spring framework is the org.springframework.beans package. Spring framework uses JavaBeans and this package provides most of the basic functionality to manipulate Java beans and provides the basic infrastructure for the other spring framework classes. This package also provides the basis for the "Dependency injection" pattern that spring is based on.
There are two ways in which clients can use the functionality of the Spring Framework--the BeanFactory and the ApplicationContext. The BeanFactory is a generic factory, which stores the information about all the Spring Beans and allows the user to instantiate beans and manage them. The BeanFactory provides programmers with the facilities to implement the basic features of the Spring Framework. The ApplicationContext builds on top of the BeanFactory and inherits all the basic features of the Spring Framework. Apart from the basic features, ApplicationContext provides additional features like Event management, internationalization support and resource management.
The BeanFactory is particularly useful in low memory situations like in an Applet where having the whole API would be overkill. It provides the basic spring framework features and does not bring all the excess baggage that ApplicationContext has. ApplicationContext helps the user to use spring in a framework oriented way while the BeanFactory offers a programmatic approach
Two way to configure Spring IOC container
a) xml file: Developer can define the bean configuration in xml file and then instruct the Spring to use the xml file to configure the beans. The xml file configuration method is targeted to infrastructure providers.
b) Annotation: The @configuration spring annotation can also be used to configure the Spring IOC container. Here programmer add the @configuration to the Java class and this class is considered as special configuration class. The @configuration annotation method is targeted the developers. This is pure-java approach to configure the Spring IoC Container. The @Bean tag is used to define the bean, and the Spring framework executes the method and then register the object returned. By default the name of the method is used as the bean name.
Procedure to run spring in Eclipse:
Step 1:
Now we will create a new project in Eclipse IDE and then add the library files.
Click next. Give any name to the project, say "Spring3" and then click on the "Finish" button.
Eclipse will create a new project.
Step 2:
Create a new folder "lib" in the project space to hold the Spring 3.0 libraries. Right click on the "Spring3" in the project explorer and then select new folder option as shown below:
Then in the next screen enter "lib" next to the "Folder name" text field and click on the "Finish" button.
Step 3:
Now we will add the Spring 3. libraries to the project. Extract the "spring-framework-3.0.0.RELEASE-with-docs.zip" file if you have not extracted. Now go to the "dist" directory of the and then copy all the jar files (Ctrl+C) and paste on the lib directory (of our project) in the Eclipse IDE.
Then find the commons-logging.jar from extracted folder and also copy this file into Eclipse IDE. You will find this library into spring-framework-3.0.0.RELEASE-with-docs\spring-framework-3.0.0.RELEASE\projects\spring-build\lib\ivy folder.
Step 4:
Now all all the libraries to "Java Build Path". Right click on the "Spring3" in project explorer and then select properties. Then select "Java Build Path" --> Libraries and then click on the "Add JARs" button. And add all the libraries to Java Build Path.
Then click on the "OK" button. This will add all the libraries to the project. Now we can proceed with our Spring 3 Hello World example.
Step 5:
Create a new package net.roseindia to hold the java files. Right click on the "Spring3" and then select New --> Package. Then provide the package name as net.roseindia and click on the "Finish" button.
Step 6:
Create a new Java file Spring3HelloWorld.java under the package net.roseindia and add the following code:
package net.roseindia;
public class Spring3HelloWorld {
public void sayHello(){
System.out.println("Hello Spring 3.0");
}
}
In the above class we have created a method sayHello() which prints the "Hello Spring 3.0" on the console. In this section we will use the Spring framework to manage the Spring3HelloWorld bean, and then get the bean from the Spring runtime environment (Spring context) and the call the sayHello() method. In the next step we will xml file which will be used as Metadata to configure the bean.
Step 7:
Now create a new xml (SpringHelloWorld.xml) file using Eclipse IDE.
Add the following code to the xml file:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
class="net.roseindia.Spring3HelloWorld" />
The above xml file declares the spring bean "Spring3HelloWorldBean" of the class net.roseindia.Spring3HelloWorld. The
Step 8:
Now create a java file (Spring3HelloWorldTest.java) into net.roseindia package and add the following code:
package net.roseindia;
import java.util.Map;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.Assert;
public class Spring3HelloWorldTest {
public static void main(String[] args) {
XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
"SpringHelloWorld.xml"));
Spring3HelloWorld myBean = (Spring3HelloWorld) beanFactory
.getBean("Spring3HelloWorldBean");
myBean.sayHello();
}
}
In the above code we have created the instance of XmlBeanFactory and the retrieved the "Spring3HelloWorldBean". Then we can call the sayHello() method on the bean. The XmlBeanFactory class is extension of DefaultListableBeanFactory that reads bean definitions from an XML document. In our case it reads the bean definitions from SpringHelloWorld.xml file.
Step 9:
To run the code in Eclipse open Spring3HelloWorldTest.java in the editor and then right click and select Run as --> Java Application. This execute the Spring3HelloWorldTest.java file and following output will be displayed in the console.
Features of Spring Framework:
• Transaction Management: Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments.
• JDBC Exception Handling: The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy
• Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS.
• AOP Framework: Spring is best AOP framework
• MVC Framework: Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.
No comments:
Post a Comment