What is Spring?

Spring is grate framework for development of Enterprise grade applications. Spring is a light-weight framework for the development of enterprise-ready applications. Spring can be used to configure declarative transaction management, remote access to your logic using RMI or web services, mailing facilities and various options in persisting your data to a database. Spring framework can be used in modular fashion, it allows to use in parts and leave the other components which is not required by the application. 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 Architecture
Spring is well-organized architecture consisting of seven modules. Modules in the Spring framework are: 1. Spring AOP One of the key components of Spring is the AOP framework. AOP is used in Spring:  To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on Spring's transaction abstraction.  To allow users to implement custom aspects, complementing their use of OOP with AOP

2. Spring ORM The ORM package is related to the database access. It provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis. 3. Spring Web The Spring Web module is part of Spring’s web application development stack, which includes Spring MVC. 4. Spring DAO The DAO (Data Access Object) support in Spring is primarily for standardizing the data access work using the technologies like JDBC, Hibernate or JDO. 5. Spring Context This package builds on the beans package to add support for message sources and for the Observer design pattern, and the ability for application objects to obtain resources using a consistent API. 6. Spring Web MVC This is the Module which provides the MVC implementations for the web applications. 7. Spring Core The Core package is the most import component of the Spring Framework. This component provides the Dependency Injection features. The BeanFactory provides a factory pattern which separates the dependencies like initialization, creation and access of the objects from your actual program logic. The following diagram represents the Spring Framework Architecture

Spring Framework Architecture

Spring Download - Downloading and Installing Spring Framework
Spring Framework is available for download from its official website. The latest version of the spring framework at the time of writing this tutorial is Spring 2.5.1, which available for download at from its official website. Spring 2.5.1 is one the most advance light weight framework for develop enterprise applications. The most exiting feature is Custom components. Spring ships with few namespaces such as jee, aop, util, and etc, now you can write your own custom namespaces. So, let's start experimenting with the spring framework. Download Spring Framework 2.5.1 Visit the Spring official website at http://www.springframework.org/download

To download the Spring Frame work click on "Download" link.

Then select "spring-framework-2.5.1-with-dependencies.zip" link. This download contains all the dependencies required to run the spring framework.

Save the downloaded file onto your favorite directory. In the next section we will extract the download and explore the different directories of the downloaded file.

Spring Framework Install
Spring Framework Install - a quick tutorial to install Spring Framework on your development environment. In the last section we downloaded the latest version of Spring framework (spring-framework-2.5.1-with-dependencies.zip). In this section we will extract the downloaded file and pick the required libraries and then install in our development environment. Extracting Spring download Now extract the downloaded file (spring-framework-2.5.1-with-dependencies.zip) into your favorite directory. Depending upon the system speed it will take around 1 minute. Once extract go to the extracted folder and you will find many files. Here are some of the file names:
         

build.bat build.xml build-continuous.xml changelog.txt license.txt maven.xml notice.txt project.properties readme.txt tests.bat

Here is the screen shot of the directory:

The dist directory of the spring framework contains the spring modules (modules directory) library files. We are mostly concern with these jar files. We will copy these jar files into our development environment. These jar files are:
             

spring-aop.jar spring-beans.jar spring-context.jar spring-context-support.jar spring-core.jar spring-jdbc.jar spring-jms.jar spring-orm.jar spring-test.jar spring-tx.jar spring-web.jar spring-webmvc.jar spring-webmvc-portlet.jar spring-webmvc-struts.jar

We will be using these libraries as per our requirement in our application. Another most important directory is "lib", which contains required library files for the application. The following libraries are included in the Spring Framework distribution because they are required either for building the framework or for running the sample apps. Note that each of these libraries is subject to the respective license; check the respective project distribution/website before using any of them in your own applications. * ant/ant.jar, ant/ant-launcher.jar, ant-trax.jar, ant-junit.jar - Ant 1.7 (http://ant.apache.org) - used to build the framework and the sample apps * antlr/antlr-2.7.6.jar - ANTLR 2.7.6 (http://www.antlr.org) - required for running PetClinic (by Hibernate) * aopalliance/aopalliance.jar - AOP Alliance 1.0 (http://aopalliance.sourceforge.net) - required for building the framework - included in spring.jar and spring-aop.jar * aspectj/aspectjweaver.jar, aspectj/aspectjrt.jar, (aspectj/aspectjtools.jar) - AspectJ 1.5.4 (http://www.aspectj.org) - required for building the framework - required at runtime when using Spring's AspectJ support NOTE: aspectjtools.jar is not included in the Spring distribution because of its size. It needs to be taken from the AspectJ distribution or from Spring CVS. Note that this is only necessary if you want to rebuild the Spring jars including the AspectJ aspects. * axis/axis.jar, axis/wsdl4j.jar - Apache Axis 1.4 (http://ws.apache.org/axis) - required for building the framework - required for running JPetStore * bsh/bsh-2.0b4.jar - BeanShell 2.0 beta 4 (http://www.beanshell.org) - required for building the framework - required at runtime when using Spring's BeanShell support * bnd/bnd.jar - BND tool 0.0.208 (http://www.aqute.biz/Code/Bnd) - required for adding OSGi entries to the jar manifests at build time

* c3p0/c3p0-0.9.1.2.jar - C3P0 0.9.1.2 connection pool (http://sourceforge.net/projects/c3p0) - required for building the framework - required at runtime when using Spring's C3P0NativeJdbcExtractor - required for running Image Database * caucho/hessian-3.1.3.jar - Hessian/Burlap 3.1.3 (http://www.caucho.com/hessian) - required for building the framework - required at runtime when using Spring's Hessian/Burlap remoting support * cglib/cglib-nodep-2.1_3.jar - CGLIB 2.1_3 with ObjectWeb ASM 1.5.3 (http://cglib.sourceforge.net) - required for building the framework - required at runtime when proxying full target classes via Spring AOP * commonj/commonj-twm.jar - CommonJ TimerManager and WorkManager API 1.1 (http://dev2dev.bea.com/wlplatform/commonj/twm.html) - required for building the framework - required at runtime when using Spring's CommonJ support * concurrent/backport-util-concurrent.jar - Dawid Kurzyniec's JSR-166 backport, version 3.0 (http://dcl.mathcs.emory.edu/util/backport-util-concurrent) - required for building the framework - required at runtime when using Spring's backport-concurrent support * dom4j/dom4j-1.6.1, dom4j/jaxen-1.1-beta-7.jar - DOM4J 1.6.1 XML parser (http://www.dom4j.org) - required for running PetClinic (by Hibernate) * easymock/easymock.jar, easymock/easymockclassextension.jar - EasyMock 1.2 (JDK 1.3 version) (http://www.easymock.org) - required for building and running the framework's test suite * ehcache/ehcache-1.3.0.jar - EHCache 1.3.0 (http://ehcache.sourceforge.net) - required for building the framework - required at runtime when using Spring's EHCache support - required for running PetClinic (by Hibernate) * freemarker/freemarker.jar - FreeMarker 2.3.11 (http://www.freemarker.org) - required for building the framework - required at runtime when using Spring's FreeMarker support

* glassfish/glassfish-clapi.jar - GlassFish ClassLoader API extract (http://glassfish.dev.java.net) - required for building the framework * groovy/groovy-1.5.1.jar - Groovy 1.5.1 (http://groovy.codehaus.org) - required for building the framework - required at runtime when using Spring's Groovy support * hibernate/hibernate3.jar - Hibernate 3.2.5 (http://www.hibernate.org) - required for building the framework - required at runtime when using Spring's Hibernate support * hibernate/hibernate-annotation.jar - Hibernate Annotations 3.3.0 (http://www.hibernate.org) - required for building the "tiger" part of the framework - required at runtime when using Spring's Hibernate Annotations support * hibernate/hibernate-entitymanager.jar - Hibernate EntityManager 3.3.1 (http://www.hibernate.org) - required for building the "tiger" part of the framework - required at runtime when using Spring's Hibernate-specific JPA support * hibernate/jboss-archive-browsing.jar - JBoss Archive Browsing 5.0.0 alpha - required at runtime when using Hibernate EntityManager * hsqldb/hsqldb.jar - HSQLDB 1.8.0.1 (http://hsqldb.sourceforge.net) - required for running JPetStore and PetClinic * ibatis/ibatis-2.3.0.677.jar - iBATIS SQL Maps 2.3.0 b677 (http://ibatis.apache.org) - required for building the framework - required at runtime when using Spring's iBATIS SQL Maps 2.x support * itext/iText-2.0.7.jar - iText PDF 2.0.7 (http://www.lowagie.com/itext) - required for building the framework - required at runtime when using Spring's AbstractPdfView * j2ee/activation.jar - JavaBeans Activation Framework 1.1 (http://java.sun.com/products/javabeans/glasgow/jaf.html)

- required at runtime when using Spring's JavaMailSender on JDK < 1.6 * j2ee/common-annotations.jar - JSR-250 Common Annotations (http://jcp.org/en/jsr/detail?id=250) - required at runtime when using Spring's Common Annotations support on JDK < 1.6 * j2ee/connector.jar - J2EE Connector Architecture 1.5 (http://java.sun.com/j2ee/connector) - required for building the framework * j2ee/ejb-api.jar - Enterprise JavaBeans API 3.0 (http://java.sun.com/products/ejb) - required for building the framework - required at runtime when using Spring's EJB support * j2ee/el-api.jar - JSP 2.1's EL API (http://java.sun.com/products/jsp), as used by JSF 1.2 - required for building the framework - required at runtime when using Spring's JSF 1.2 support * j2ee/jaxrpc.jar - JAX-RPC API 1.1 (http://java.sun.com/xml/jaxrpc) - required for building the framework - required at runtime when using Spring's JAX-RPC support * j2ee/jms.jar - Java Message Service API 1.1 (java.sun.com/products/jms) - required for building the framework - required at runtime when using Spring's JMS support * j2ee/jsf-api.jar - JSF API 1.1 (http://java.sun.com/j2ee/javaserverfaces) - required for building the framework - required at runtime when using Spring's JSF support * j2ee/jsp-api.jar - JSP API 2.0 (http://java.sun.com/products/jsp) - required for building the framework - required at runtime when using Spring's JSP support * j2ee/jstl.jar - JSP Standard Tag Library API 1.1 (http://java.sun.com/products/jstl) - required for building the framework - required at runtime when using Spring's JstlView * j2ee/jta.jar

- Java Transaction API 1.1 (http://java.sun.com/products/jta) - required for building the framework - required at runtime when using Spring's JtaTransactionManager * j2ee/mail.jar - JavaMail 1.4 (http://java.sun.com/products/javamail) - required for building the framework - required at runtime when using Spring's JavaMailSender * j2ee/persistence.jar - Java Persistence API 1.0 (http://www.oracle.com/technology/products/ias/toplink/jpa) - required for building the framework - required at runtime when using Spring's JPA support * j2ee/rowset.jar - JDBC RowSet Implementations 1.0.1 (http://java.sun.com/products/jdbc) - required at runtime when using Spring's RowSet support on JDK < 1.5 * j2ee/servlet-api.jar - Servlet API 2.4 (http://java.sun.com/products/servlet) - required for building the framework - required at runtime when using Spring's web support * jakarta-commons/commons-attributes-api.jar, jakarta-commons/commons-attributescompiler.jar - Commons Attributes 2.2 (http://jakarta.apache.org/commons/attributes) - commons-attributes-api.jar has a patched manifest (not declaring QDox and Ant as required extensions) - required for building the framework - required at runtime when using Spring's Commons Attributes support * jakarta-commons/commons-beanutils.jar - Commons BeanUtils 1.7 (http://jakarta.apache.org/commons/beanutils) - required for running JPetStore's Struts web tier * jakarta-commons/commons-collections.jar - Commons Collections 3.2 (http://jakarta.apache.org/commons/collections) - required for building the framework - required for running PetClinic, JPetStore (by Commons DBCP, Hibernate) * jakarta-commons/commons-dbcp.jar - Commons DBCP 1.2.2 (http://jakarta.apache.org/commons/dbcp) - required for building the framework - required at runtime when using Spring's CommonsDbcpNativeJdbcExtractor - required for running JPetStore

* jakarta-commons/commons-digester.jar - Commons Digester 1.6 (http://jakarta.apache.org/commons/digester) - required for running JPetStore's Struts web tier * jakarta-commons/commons-discovery.jar - Commons Discovery 0.2 (http://jakarta.apache.org/commons/discovery) - required for running JPetStore (by Axis) * jakarta-commons/commons-fileupload.jar - Commons FileUpload 1.2 (http://jakarta.apache.org/commons/fileupload) - required for building the framework - required at runtime when using Spring's CommonsMultipartResolver * jakarta-commons/commons-httpclient.jar - Commons HttpClient 3.1 (http://hc.apache.org/httpclient-3.x) - required for building the framework - required at runtime when using Spring's CommonsHttpInvokerRequestExecutor * jakarta-commons/commons-io.jar - Commons IO 1.3.1 (http://jakarta.apache.org/commons/io) - required at runtime when using Spring's CommonsMultipartResolver (by Commons FileUpload) * jakarta-commons/commons-lang.jar - Commons Lang 2.2 (http://jakarta.apache.org/commons/lang) - required at runtime when using Spring's OpenJPA support (by OpenJPA) * jakarta-commons/commons-logging.jar - Commons Logging 1.1 (http://jakarta.apache.org/commons/logging) - required for building the framework - required at runtime, as Spring uses it for all logging * jakarta-commons/commons-pool.jar - Commons Pool 1.3 (http://jakarta.apache.org/commons/pool) - required for running JPetStore and Image Database (by Commons DBCP) * jakarta-commons/commons-validator.jar - Commons Validator 1.1.4 (http://jakarta.apache.org/commons/validator) - required for running JPetStore's Struts web tier on servers that eagerly load tag libraries (e.g. Resin) * jakarta-taglibs/standard.jar - Jakarta's JSTL implementation 1.1.2 (http://jakarta.apache.org/taglibs) - required for running JPetStore, PetClinic, Countries * jamon/jamon-2.4.jar

- JAMon API (Java Application Monitor) 2.4 (http://www.jamonapi.com) - required for building the framework - required at runtime when using Spring's JamonPerformanceMonitorInterceptor * jarjar/jarjar.jar - Jar Jar Links 1.0 RC5 (http://code.google.com/p/jarjar) - required for building the framework jars * jasperreports/jasperreports-2.0.2.jar - JasperReports 2.0.2 (http://jasperreports.sourceforge.net) - required for building the framework - required at runtime when using Spring's JasperReports support * jaxws/jws-api.jar, jaxws/jaxws-api.jar, jaxws/jaxb-api.jar, jaxws/saaj-api.jar - JAX-WS 2.1.2 API (https://jax-ws.dev.java.net) - required at runtime when running Spring's JAX-WS support tests on JDK < 1.6 * jdo/jdo2-api.jar - JDO API 2.0 (http://db.apache.org/jdo) - required for building the framework - required at runtime when using Spring's JDO support (or jdo.jar for JDO 1.0) * jexcelapi/jxl.jar - JExcelApi 2.6.6 (http://jexcelapi.sourceforge.net) - required for building the framework - required at runtime when using Spring's AbstractJExcelView * jmx/jmxri.jar - JMX 1.2.1 reference implementation - required at runtime when using Spring's JMX support on JDK < 1.5 * jmx/jmxremote.jar - JMX Remote API 1.0.1 reference implementation - required at runtime when using Spring's JMX support on JDK < 1.5 * jmx/jmxremote_optional.jar - JMXMP connector (from JMX Remote API 1.0.1 reference implementation) - required at runtime when using the JMXMP connector (even on JDK 1.5) * jotm/jotm.jar - JOTM 2.0.10 (http://jotm.objectweb.org) - required for building the framework - required at runtime when using Spring's JotmFactoryBean * jotm/xapool.jar - XAPool 1.5.0 (http://xapool.experlog.com, also included in JOTM)

- required for building the framework - required at runtime when using Spring's XAPoolNativeJdbcExtractor * jruby/jruby.jar - JRuby 1.0.1 (http://jruby.codehaus.org) - required for building the framework - required at runtime when using Spring's JRuby support * junit/junit-3.8.2.jar, junit/junit-4.4.jar - JUnit 3.8.2 / 4.4 (http://www.junit.org) - required for building and running the framework's test suite * log4j/log4j-1.2.14.jar - Log4J 1.2.14 (http://logging.apache.org/log4j) - required for building the framework - required at runtime when using Spring's Log4jConfigurer * oc4j/oc4j-clapi.jar - Oracle OC4J 10.1.3.1 ClassLoader API extract (http://www.oracle.com/technology/tech/java/oc4j) - required for building the framework * openjpa/openjpa-1.0.1.jar - OpenJPA 1.0.1 (http://openjpa.apache.org) - required for building the framework - required at runtime when using Spring's JPA support with OpenJPA as provider * poi/poi-3.0.1.jar - Apache POI 3.0.1 (http://jakarta.apache.org/poi) - required for building the framework - required at runtime when using Spring's AbstractExcelView * portlet/portlet-api.jar - Portlet API 1.0 (http://jcp.org/aboutJava/communityprocess/final/jsr168) - required for building the framework - required at runtime when using Spring's Portlet support * qdox/qdox-1.5.jar - QDox 1.5 (http://qdox.codehaus.org) - used by Commons Attributes 2.2 to parse source-level metadata in the build process - required for building the framework and the attributes version of JPetStore * quartz/quartz-all-1.6.0.jar - Quartz 1.6.0 (http://www.opensymphony.com/quartz) - required for building the framework - required at runtime when using Spring's Quartz scheduling support

* serp/serp-1.13.1.jar - Serp 1.13.1 (http://serp.sourceforge.net) - required at runtime when using OpenJPA * struts/struts.jar - Apache Struts 1.2.9 (http://jakarta.apache.org/struts) - required for building the framework - required at runtime when using the Struts 1.x support or Tiles 1.x TilesView - required for running JPetStore's Struts web tier * testng/testng-5.5-jdk15.jar - TestNG 5.5 (http://testng.org) - required for building and running the framework's test suite * tiles/tiles-api-2.0.5.jar, tiles/tiles-core-2.0.5.jar, tiles/tiles-jsp-2.0.5.jar - Apache Tiles 2.0.5 (http://tiles.apache.org) - required for building the framework - required at runtime when using the Tiles2 TilesView * tomcat/catalina.jar, tomcat/naming-resources.jar - Apache Tomcat 5.5.23 (http://tomcat.apache.org) - required for building the Tomcat-specific weaver * toplink/toplink-api.jar - Oracle TopLink 10.1.3 API (http://www.oracle.com/technology/products/ias/toplink) - required for building the framework - replaced with full toplink.jar at runtime when using Spring's TopLink support * toplink/toplink-essentials.jar - Oracle TopLink Essentials v2 b41 (http://www.oracle.com/technology/products/ias/toplink/jpa) - required for building the framework - required at runtime when using Spring's JPA support with TopLink as provider * velocity/velocity-1.5.jar - Velocity 1.5 (http://jakarta.apache.org/velocity) - required for building the framework - required at runtime when using Spring's VelocityView * velocity/velocity-tools-view-1.4.jar - Velocity Tools 1.4 (http://jakarta.apache.org/velocity/tools) - required for building the framework - required at runtime when using VelocityView's support for Velocity Tools You can use above libraries in your application as per your requirement.

In the next section I will show you how to setup development environment step-by-step.

Spring Injection Example
XML Bean-Injection, The given example below gives the brief description of the extension name spaces that can be used in the spring framework With the use of extensible name space you can make Spring configuration file more simpler to use for many tasks which can occurs repeatedly . Extension namespaces also allows us to supply property values by using attributes . xmlns:p="http://www.springframework.org/schema/p":-Here we have introduced namespace:"p" that cannot be validated. <bean id="mybean" class="Inject">:- Here "Inject" is the name of the bean class which would be referred in the xml file with the id "mybean". p:name="Girish" :-Here we simply use the property name in the "p" namespace, as in "p:name". context.xml

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/springbeans.xsd"> <bean id="mybean" class="Inject" p:name="Girish" p:age="24" p:address="Noida" p:company="Roseindia.net" p:email="girish@roseindia.net"/> </beans>

Main.java This is the file through which we are retrieving the property of the bean defined above. Some of the methods which are used here are as follows:-

XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("context. xml")):-This method creates an instance of the XmlBeanFactory which is used to read bean definition from an XML document new ClassPathResource("context.xml"):-Creates a new ClassPathResource for ClassLoader .Here the context.xml is the file which is to be loaded. String.format("Name: %s\n" +"Age: %d\n" ):-This method formats an object to produce a string. Here %s:-is for accessing String value. %d:-is for accessing Integer value.
import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Main { public static void main(String[] args) { XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource( "context.xml")); Inject demo = (Inject) beanFactory.getBean("mybean"); System.out.println(demo); } } class Inject { private private private private private String name; int age; String company; String email; String address;

public void setAddress(String address) { this.address = address; } public void setCompany(String company) { this.company = company; } public void setEmail(String email) { this.email = email; } public void setAge(int age) { this.age = age; } public void setName(String name) { this.name = name;

} @Override public String toString() { return String.format("Name: %s\n" + "Age: %d\n" + "Address: %s\n" + "Company: %s\n" + "E-mail: %s", this.name, this.age, this.address, this.company, this.email); } }

Output of the Spring Injection Example program Nov 25, 2008 1:03:13 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [context.xml] Name: Girish Age: 24 Address: Noida Company: Roseindia.net E-mail: girish@roseindia.net BUILD SUCCESSFUL (total time: 1 second)

Spring Batch Example
JDBC Template Batch update example, In the tutorial we have discussed about batchUpdate() method of class JdbcTemplate in Spring framework. The Batch update methods are used to executes multiple SQL updates query on a single JDBC Statement. The example given below consists of the code to delete and update data of the table Simultaneously. context.xml

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:lang="http://www.springframework.org/schema/lang" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://192.168.10.75:3306/komal"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler"> <property name="nativeJdbcExtractor" ref="nativeJdbcExtractor"/> </bean> <bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor"/> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> </beans>

Main.java ApplicationContext ac = new ClassPathXmlApplicationContext("context.xml", Main.class):-ApplicationContext is the interface that is used to provide Bean factory methods for accessing application components. Here we Creates an instance of this interface to access context.xml and Main.java. DataSource source = (DataSource) ac.getBean("dataSource"):-Data source is an Interface which provides a way for connecting to the physical data source. Here we created datasource for making connection to our xml document in which we have declared the bean. jt.batchUpdate(new String[]{"update employee set departement = 'Finance#'", "delete from employee where EmployeeId =31" }):-With the use of this method we are

executing two SQLquery simultaneously. This method executes multiple Sql updates on a single JDBC statement.
import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; class Main { public static void main(String args[]) { try { ApplicationContext ac = new ClassPathXmlApplicationContext("context.xml", Main.class); DataSource source = (DataSource) ac.getBean("dataSource"); JdbcTemplate jt = new JdbcTemplate(source); jt.batchUpdate(new String[]{"update employee set departement = 'Finance#'", "delete from employee where EmployeeId =31" }); System.out.println("Data updated successfully"); } catch (Exception e) { e.printStackTrace(); } } }

Output of the program
Data updated successfully BUILD SUCCESSFUL (total time: 2 seconds)

Table before updation

Table after updation

Inheritance in Spring
Inheritance Demo, In the example given below we are going to tell about the inheritance in the Spring framework. By inheritance we mean a way of forming new classes using classes that have already been defined. Here we have created a simple bean and used this bean as a template for creating other beans. <bean id="parent" class="mybean" >:-Creates a Parent bean which would be used as a template for creating other beans. Here "mybean" is the name of the bean class which would be referred in the xml file with the id "parent". <bean id="child" class="mybean" parent="parent">:-Creates a child bean which would be inheriting from the parent bean defined above. parent="parent":-Specify that this bean is inheriting the properties of some other bean. <bean id="parent" class="mybean" > <property name="name" value="Roseindia.net"/> </bean> <bean id="child" class="mybean" parent="parent"> <property name="address" value="Rohini"/> </bean> context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/springbeans.xsd"> <bean id="parent" class="mybean" > <property name="name" value="Roseindia.net"/> </bean> <bean id="child" class="mybean" parent="parent"> <property name="address" value="Rohini"/> </bean> <bean id="subchild" class="mybean" parent="parent"/> </beans>

Main.java

This is the file through which we are retrieving the property of the bean defined above. Some of the methods which are used here are as follows:XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("context. xml")):-This method creates an instance of the XmlBeanFactory which is used to read bean definition from an XML document new ClassPathResource("context.xml"):-Creates a new ClassPathResource for ClassLoader .Here the context.xml is the file which is to be loaded. (bf.getBean("child")):-This method returns an instance of the bean named "child", which is shared or independent, of the given bean name. (bf.getBean("subchild")):-This method returns an instance of the bean named "subchild", which is shared or independent, of the given bean name. stringBuilder.append("Bean"):-This is the method of the class string Builder which appends the specified string to this character sequence.

import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Main { public static void main(String[] args) throws Exception { XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("context.xml")); System.out.println("===============Inheritance demo================="); System.out.println(bf.getBean("child")); System.out.println(bf.getBean("subchild")); } } class mybean { private String name; private String address; public void setName(String name) { this.name = name; } public void setAddress(String address) { this.address = address; } @Override public String toString() { final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Bean"); stringBuilder.append("{name='").append(name).append('\''); stringBuilder.append(", address=").append(address);

stringBuilder.append('}'); return stringBuilder.toString(); } }

Output of the program Nov 25, 2008 3:39:29 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [context.xml] ===============Inheritance demo================= Bean{name='Roseindia.net', address=Rohini} Bean{name='Roseindia.net', address=null} BUILD SUCCESSFUL (total time: 1 second)

Spring Hello World Application
Hello World Example using Spring, The tutorial given below describes you the way to make a spring web application that displays Hello World message on the Browser. For that we have created a file called "applicationContext.xml", which defines the bean name, their properties as well as their values. Required fields:1)class name: A class name is the implementation of the bean class that is described in the bean definition. 2)bean behavioral configuration elements: Here we define the bean behavior that is bean initialization, dependency checking mode, destruction methods etc. 3)constructor arguments and property values :-Defines the no of arguments and the property values that are to be set in the newly created bean. Note:- We have not defined any of these behavior in our context file since we haven't created any of the bean to be used.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> </beans>

dispatcher-servlet. xml:-This is the file from which the mapping from actions to controllers is done .We have used ControllerClassNameHandlerMapping and SimpleUrlHandlerMapping classes to do such mapping. ControllerClassNameHandlerMapping class generate URL path mappings from the class names of the Controller.SimpleUrlHandlerMapping maps URLs to the request handler beans. p:viewName="index" />:This is the ParameterizableViewController. With the use of this controller we can view the index. p:suffix=".jsp" />:-This is InternalResourceViewResolver. With the use of this we can map this name to an actual jsp page.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean class="org.springframework.web.servlet.mvc.support.Controller ClassNameHandlerMapping"/> <bean id="urlMapping" class="org.springframework.web.servlet.handle r.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/index.htm">indexController </prop> </props> </property> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceV iewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> <bean name="indexController" class="org.springframework.web.servlet.mvc.ParameterizableVie wController"

p:viewName="index" /> </beans>

redirect.jsp:<% response.sendRedirect("index.htm"); %>:-This is a method of Interface HttpServletResponse that is used to sends a temporary redirect response to the client using the specified redirect location.
<%@page contentType="text/html" pageEncoding="UTF8"%> <% response.sendRedirect("index.htm"); %>

index.jsp:-This is the page in which the message is to be displayed.
<%@page contentType="text/html" pageEncoding="UTF8"%> <!DOCTYPE HTML PUBLIC "//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="ContentType" content="text/html; charset=UTF-8"> <title>Hello World-Spring</title> <h1>Hello World-Spring</h1> <hr></hr> </head> <body> <h2>Hello World</h2> </body> </html>

Output of the program

Calling Constructor in Spring
In the given example you will be learning about a constructor and how to call a constructor in the Spring. Declaring constructor injection in the Spring framework is generally done in the bean section of the configuration file that is the context.xml file. Steps to declare Constructor Injection: 1)Set the constructor declaration 2)Pass the value to the constructor. This tutorial describes the way of defining constructor in the xml document and retrieving the values defined in the constructor using java file.

<constructor-arg> <util:map> <entry key="CompanyName" value="Roseindia.net"/> <entry key="Address" value="Rohini"/> </util:map> </constructor-arg> <constructor-arg>:-This is the way to declare the constructor injection consisting of arguments. The use of this injection is to tell the container that the application wants to use the Constructor Injection. <entry key="CompanyName" value="Roseindia.net"/>:-Passing the value to the constructor is usually done through the <value>element. Here we have pass "Roseindia.net " as the company name. context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="

http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/springbeans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/springutil.xsd"> <bean id="encyclopedia" name="mybean" class="Configure"> <constructor-arg> <util:map> <entry key="CompanyName" value="Roseindia.net"/> <entry key="Address" value="Rohini"/> </util:map> </constructor-arg> </bean> <bean id="company" class="Companyinformation"> <property name="encyclopedia" ref="mybean"/> </bean> </beans>

Here is the file named Main.java through which we are retrieving the properties of the bean which we have defined in the above file i.e. context.xml XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("context .xml")):-Here we are creating an instance of the XmlBeanFactory which is used to read bean definition from an XML document new ClassPathResource("context.xml"):-Creates a new ClassPathResource for ClassLoader .Here the context.xml is the file which is to be loaded. Main.java
import import import import java.util.Map; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.util.Assert;

public class Main { public static void main(String[] a) { XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathRe source("context.xml")); company mycomp = (company) beanFactory.getBean("company"); System.out.println("Name of the company is: " + mycomp.Name()); System.out.println("Address of the company is: " + mycomp.addre ss()); } } interface company {

String Name(); String address(); } interface Detail { String find(String entry); }

class Companyinformation implements company { private Detail detail; public String Name() { String name = this.detail.find("CompanyName"); return String.valueOf(name); } public String address() { String add = this.detail.find("Address"); return String.valueOf(add); } public void setEncyclopedia(Detail d) { this.detail = d; } } class Configure implements Detail { private Map map; public Configure(Map map) { Assert.notNull(map, "Arguments cannot be null."); this.map = map; } public String find(String s) { return (String) this.map.get(s); } }

Output of the program Nov 26, 2008 12:48:55 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [context.xml] Name of the company is: Roseindia.net Address of the company is: Rohini BUILD SUCCESSFUL (total time: 1 second)

init Method in Spring
Calling Bean using init() method in Spring, this section describes the way to initialize a bean through its lifecycle events using the init() method .Here we have defined the property and values of the bean using the init method as shown below:<bean id="mybean" class="Bean" init-method="init">:-Here "Bean" is the name of the bean class which would be referred in the xml file with the id "mybean". init-method="init":-Specify the init method named "init" in the configuration file. <property name="name"> <value>Roseindia.net</value>:-Here the <property> element is used to declare the attributes and to pass the desired value to the property element, the <value> element is used. Here the property name is "name"and its value is "Roseindia.net".

<bean id="mybean" class="Bean" init-method="init"> <property name="name"> <value>Roseindia.net</value> </property> <property name="address"> <value>Rohini</value> </property> <property name="type"> <value>Software Development Company</value> </property> </bean> initMethod.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="mybean" class="Bean" init-method="init"> <property name="name"> <value>Roseindia.net</value> </property> <property name="address"> <value>Rohini</value> </property> <property name="type">

<value>Software Development Company</value> </property> </bean> </beans>

Here is the file named SimpleBean.java through which we are retrieving the properties of the bean which we have defined in the above file i.e. initMethod.xml. BeanFactory factory = new XmlBeanFactory(new FileSystemResource("initMethod .xml")):-Creates an instance of the XmlBeanFactory which is used to read bean definition from an XML document. SimpleBean.java
import import import import org.springframework.beans.factory.BeanCreationException; org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.FileSystemResource;

public class Bean { private private private private static String String String final String DEFAULT_NAME = "Girish"; name = null; address = null; type = null;

public void setName(String name) { this.name = name; } public void setAddress(String address) { this.address = address; } public void setType(String type) { this.type = type; } public void init() { System.out.println("Initializing bean"); if (name == null) { System.out.println("Using default name"); name = DEFAULT_NAME; } if (address == null) { System.out.println("Using default name"); address = DEFAULT_NAME; } if (type == null) { System.out.println("Using default name"); type = DEFAULT_NAME; }

} public String toString() { return "Name: " + name + "\nAddress: " + address + "\nType: " + type ; } public static void main(String[] args) { BeanFactory factory = new XmlBeanFactory(new FileSystemResource( "initMethod.xml")); Bean Bean1 = getBean("mybean", factory); } private static Bean getBean(String beanName, BeanFactory factory) { try { Bean bean = (Bean) factory.getBean(beanName); System.out.println(bean); return bean; } catch (BeanCreationException ex) { System.out.println("An error occured in bean configuration: " + ex.getMessage()); return null; } } }

Output of the program Initializing bean Name: Roseindia.net Address: Rohini Type: Software Development Company

Bean life cycle in spring
This example gives you an idea on how to Initialize bean in the program and also explains the lifecycle of bean in spring. Run the given bean example to retrieves the values of the bean using java file. Here in the file given below i.e. (context.xml) we have declare the bean definition. <bean id="Mybean" class="Bean"> <property name="company" value="Name"/> <property name="value" value="Roseindia.net"/> </bean>

Here "Bean" is the name of the bean class which would be further referred in the xml file with the id "MyBean". <property name="company" value="Name"/>:-Declares the property name of the bean and its value. context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/springbeans.xsd"> <bean id="Mybean" class="Bean"> <property name="company" value="Name"/> <property name="value" value="Roseindia.net"/> </bean> </beans>

Here is the file named Main.java through which we are retrieving the properties of the bean which we have defined in the above file i.e. context.xml XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("context .xml")):-Here we are creating an instance of the XmlBeanFactory which is used to read bean definition from an XML document new ClassPathResource("context.xml"):-Creates a new ClassPathResource for ClassLoader .Here the context.xml is the file which is to be loaded. class BeanSupport implements InitializingBean :-Here the InitializingBean interface is implemented by bean class. The use of this interface here is to do some post processing actions when all the properties have been set by the Bean Factory.. @Override public String toString() { return String.format("%s : \"%s\"", this.company, getValue()); } Here the method toString() is overridden which is returning the the company name and value that has been defined in the context.xml file. Main.java

import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Main { public static void main(String[] args) throws Exception { XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("context.xml")); System.out.println(factory.getBean("Mybean")); } } class Bean extends BeanSupport { private String company; public void setCompany(String company) { this.company = company; } @Override public String toString() { return String.format("%s : \"%s\"", this.company, getValue()); } } class BeanSupport implements InitializingBean { private String value; public final void afterPropertiesSet() throws Exception { } public final void setValue(String value) { this.value = value; } protected final String getValue() { return this.value; } }

Output of the program Nov 25, 2008 5:25:41 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [context.xml] Name : "Roseindia.net" BUILD SUCCESSFUL (total time: 1 second)

Sign up to vote on this title
UsefulNot useful