easy spring frmwrk

Upload: neeldk

Post on 14-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 Easy Spring Frmwrk

    1/32

    What is Spring?Spring is grate framework for development of Enterprise grade applications. Spring isa light-weight framework for the development of enterprise-ready applications. Spring

    can be used to configure declarative transaction management, remote access to yourlogic 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 touse 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 abstractionlayer for transaction management. This allowing the developer to add thepluggable 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 ameaningful exception hierarchy, which simplifies the error handling strategy

    Integration with Hibernate, JDO, and iBATIS: Spring provides bestIntegration services with Hibernate, JDO and iBATIS.

    AOP Framework: Spring is best AOP framework

    MVC Framework: Spring comes with MVC web application framework, builton core Spring functionality. This framework is highly configurable via strategyinterfaces, 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 AOPOne of the key components of Spring is theAOP framework. AOP is used in

    Spring:

    To provide declarative enterprise services, especially as a replacement

    for EJB declarative services. The most important such service isdeclarative transaction management, which builds on Spring's

    transaction abstraction.

    http://www.roseindia.net/spring/springarchitecture.shtmlhttp://www.roseindia.net/spring/springarchitecture.shtml
  • 7/30/2019 Easy Spring Frmwrk

    2/32

    To allow users to implement custom aspects, complementing their use of

    OOP with AOP

    2. Spring ORMThe ORMpackage 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 Springs 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 ContextThis 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 obtainresources using a consistent API.

    6. Spring Web MVCThis 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 BeanFactoryprovides 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

  • 7/30/2019 Easy Spring Frmwrk

    3/32

    Spring Framework Architecture

    Spring Download - Downloading and

    Installing Spring Framework

    Spring Framework is available for download from its official website. The latestversion 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 developenterprise applications. The most exiting feature is Custom components. Springships with few namespaces such as jee, aop, util, and etc, now you can write yourown 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

    http://www.springframework.org/downloadhttp://www.springframework.org/download
  • 7/30/2019 Easy Spring Frmwrk

    4/32

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

    Then select "spring-framework-2.5.1-with-dependencies.zip" link. This downloadcontains 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

  • 7/30/2019 Easy Spring Frmwrk

    5/32

    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 wewill extract the downloaded file and pick the required libraries and then install in our

    development environment.

    Extracting Spring downloadNow extract the downloaded file (spring-framework-2.5.1-with-dependencies.zip) intoyour favorite directory. Depending upon the systemspeed 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:

    http://www.roseindia.net/spring/spring-framework-install.shtmlhttp://www.roseindia.net/spring/spring-framework-install.shtmlhttp://www.roseindia.net/spring/spring-framework-install.shtml
  • 7/30/2019 Easy Spring Frmwrk

    6/32

    The dist directory of the spring framework contains the spring modules (modulesdirectory) 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

  • 7/30/2019 Easy Spring Frmwrk

    7/32

    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 theapplication.

    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. Notethat 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)

  • 7/30/2019 Easy Spring Frmwrk

    8/32

    - 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

  • 7/30/2019 Easy Spring Frmwrk

    9/32

    - 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

    http://www.roseindia.net/spring/spring-framework-install.shtmlhttp://www.roseindia.net/spring/spring-framework-install.shtmlhttp://www.roseindia.net/spring/spring-framework-install.shtml
  • 7/30/2019 Easy Spring Frmwrk

    10/32

    * 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

    http://www.roseindia.net/spring/spring-framework-install.shtmlhttp://www.roseindia.net/spring/spring-framework-install.shtml
  • 7/30/2019 Easy Spring Frmwrk

    11/32

    - 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-attributes-

    compiler.jar

    - Commons Attributes 2.2 (http://jakarta.apache.org/commons/attributes)

    - commons-attributes-api.jar has a patched manifest (not declaring QDox and Ant asrequired 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

  • 7/30/2019 Easy Spring Frmwrk

    12/32

    - 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 ApplicationMonitor) 2.4 (http://www.jamonapi.com)

    http://www.roseindia.net/spring/spring-framework-install.shtmlhttp://www.roseindia.net/spring/spring-framework-install.shtmlhttp://www.roseindia.net/spring/spring-framework-install.shtml
  • 7/30/2019 Easy Spring Frmwrk

    13/32

    - 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

  • 7/30/2019 Easy Spring Frmwrk

    14/32

    - 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

  • 7/30/2019 Easy Spring Frmwrk

    15/32

    * 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.

    http://www.roseindia.net/spring/spring-framework-install.shtmlhttp://www.roseindia.net/spring/spring-framework-install.shtml
  • 7/30/2019 Easy Spring Frmwrk

    16/32

    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 ofextensible name space you can make Spring configuration filemore 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 introducednamespace:"p" that cannot be validated.

    :- Here "Inject" is the name of the bean classwhich 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, asin "p:name".

    context.xml

    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 forClassLoader .Here the context.xml is the file which is to be loaded.

    http://www.roseindia.net/spring/xml-bean.shtmlhttp://www.roseindia.net/spring/xml-bean.shtmlhttp://www.roseindia.net/spring/xml-bean.shtmlhttp://www.roseindia.net/spring/xml-bean.shtmlhttp://www.roseindia.net/spring/xml-bean.shtmlhttp://www.roseindia.net/spring/xml-bean.shtmlhttp://www.roseindia.net/spring/xml-bean.shtml
  • 7/30/2019 Easy Spring Frmwrk

    17/32

    String.format("Name: %s\n" +"Age: %d\n" ):-This method formats an object toproduce 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 voidmain(String[] args) {XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(

    "context.xml"));Inject demo = (Inject) beanFactory.getBean("mybean");

    System.out.println(demo);}

    }

    class Inject {

    private String name; private int age;

    private String company; private String email;

    private String address;

    public voidsetAddress(String address) { this.address = address;

    }

    public voidsetCompany(String company) {

    this.company = company;}

    public voidsetEmail(String email) { this.email = email;

    }

    public voidsetAge(int age) { this.age = age;

    }

    public voidsetName(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",

    http://www.roseindia.net/spring/xml-bean.shtmlhttp://www.roseindia.net/spring/xml-bean.shtmlhttp://www.roseindia.net/spring/xml-bean.shtmlhttp://www.roseindia.net/spring/xml-bean.shtml
  • 7/30/2019 Easy Spring Frmwrk

    18/32

    this.name, this.age, this.address, this.company, this.email);}

    }

    Output of the Spring Injection Example program

    Nov 25, 2008 1:03:13 AMorg.springframework.beans.factory.xml.XmlBeanDefinitionReader

    loadBeanDefinitionsINFO: Loading XML bean definitions from class path resource

    [context.xml]

    Name: GirishAge: 24

    Address: Noida

    Company: Roseindia.netE-mail: [email protected]

    BUILD SUCCESSFUL (total time: 1 second)

    Spring Batch ExampleJDBC Template Batch update example, In the tutorial we have discussed about

    batchUpdate() method of class JdbcTemplate in Spring framework. The Batchupdate 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 ofthe table Simultaneously.

    context.xml

  • 7/30/2019 Easy Spring Frmwrk

    19/32

    http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.0.xsd

    http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.0.xsd

    http://www.springframework.org/schema/langhttp://www.springframework.org/schema/lang/spring-lang-2.0.xsd">

    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 anInterface 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)

    http://www.roseindia.net/spring/jdbc-template-batch-update.shtmlhttp://www.roseindia.net/spring/jdbc-template-batch-update.shtmlhttp://www.roseindia.net/spring/jdbc-template-batch-update.shtmlhttp://www.roseindia.net/spring/jdbc-template-batch-update.shtml
  • 7/30/2019 Easy Spring Frmwrk

    20/32

    ac.getBean("dataSource");JdbcTemplate jt = new JdbcTemplate(source);

    jt.batchUpdate(new String[]{"update employee setdepartement = 'Finance#'",

    "delete from employee where EmployeeId =31"});

    System.out.println("Data updated successfully");} catch (Exception e) {

    e.printStackTrace();}

    }}

    Output of the program

    Data updated successfullyBUILD SUCCESSFUL (total

    time: 2 seconds)

    Table before updation Table after updation

    Inheritance In SpringInheritance 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.

    :-Creates a Parent bean which would be usedas 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".:-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 otherbean.

    http://www.roseindia.net/spring/jdbc-template-batch-update.shtmlhttp://www.roseindia.net/spring/inheritance-demo.shtmlhttp://www.roseindia.net/spring/jdbc-template-batch-update.shtmlhttp://www.roseindia.net/spring/inheritance-demo.shtml
  • 7/30/2019 Easy Spring Frmwrk

    21/32

    context.xml

    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 forClassLoader .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 whichappends the specified string to this character sequence.

    import org.springframework.beans.factory.xml.XmlBeanFactory;

    http://www.roseindia.net/spring/inheritance-demo.shtmlhttp://www.roseindia.net/spring/inheritance-demo.shtmlhttp://www.roseindia.net/spring/inheritance-demo.shtmlhttp://www.roseindia.net/spring/inheritance-demo.shtml
  • 7/30/2019 Easy Spring Frmwrk

    22/32

    import org.springframework.core.io.ClassPathResource;

    public class Main {

    public static voidmain(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 voidsetName(String name) { this.name = name;

    }

    public voidsetAddress(String address) { this.address = address;

    }

    @Overridepublic 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 AMorg.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 ApplicationHello 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.

    http://www.roseindia.net/spring/inheritance-demo.shtmlhttp://www.roseindia.net/spring/inheritance-demo.shtml
  • 7/30/2019 Easy Spring Frmwrk

    23/32

    For that we have created a file called "applicationContext.xml", which defines thebean 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 thatis bean initialization, dependency checking mode, destruction methods etc.

    3)constructor arguments and property values :-Defines the no of arguments and theproperty 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'tcreated any of the bean to be used.

    dispatcher-servlet. xml:-This is the file from which the mapping from actions tocontrollers is done .We have used ControllerClassNameHandlerMapping and

    SimpleUrlHandlerMapping classes to do such mapping.

    ControllerClassNameHandlerMapping class generate URL path mappings from theclass names of the Controller.SimpleUrlHandlerMapping maps URLs to the request

    handler beans.

    p:viewName="index" />:This is the ParameterizableViewController. With the useof this controller we can view the index.

    p:suffix=".jsp" />:-This is InternalResourceViewResolver. With the use of this wecan map this name to an actual jsp page.

    http://www.roseindia.net/spring/helloworld.shtmlhttp://www.roseindia.net/spring/helloworld.shtml
  • 7/30/2019 Easy Spring Frmwrk

    24/32

  • 7/30/2019 Easy Spring Frmwrk

    25/32

    Calling Constructor in SpringIn 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 theconfiguration 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 andretrieving the values defined in the constructor using java file.

    :-This is the way to declare the constructor injection consisting ofarguments. The use of this injection is to tell the container that the applicationwants to

    use the Constructor Injection.

    :-Passing the value to theconstructor is usually done through the element. Here we have pass

    "Roseindia.net " as the company name.

    context.xml

  • 7/30/2019 Easy Spring Frmwrk

    26/32

    xsi:schemaLocation=" http://www.springframework.org/schema/beans

    http://www.springframework.org/schema/beans/spring-beans.xsd

    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-

    util.xsd">

    Here is the file named Main.java through which we are retrieving the properties of thebean 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 java.util.Map;import org.springframework.beans.factory.xml.XmlBeanFactory;

    import org.springframework.core.io.ClassPathResource;import org.springframework.util.Assert;

    public class Main {

    public static voidmain(String[] a) { XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("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.address()); }}

    interface company {

    String Name();

    http://www.roseindia.net/spring/calling-constructor-spring.shtmlhttp://www.roseindia.net/spring/calling-constructor-spring.shtmlhttp://www.roseindia.net/spring/calling-constructor-spring.shtmlhttp://www.roseindia.net/spring/calling-constructor-spring.shtml
  • 7/30/2019 Easy Spring Frmwrk

    27/32

    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 voidsetEncyclopedia(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 AMorg.springframework.beans.factory.xml.XmlBeanDefinitionReader

    loadBeanDefinitionsINFO: Loading XML bean definitions from class path resource

    [context.xml]

    Name of the company is: Roseindia.net

    Address of the company is: RohiniBUILD SUCCESSFUL (total time: 1 second)

  • 7/30/2019 Easy Spring Frmwrk

    28/32

    init Method in SpringCalling Bean using init() method in Spring, this section describes the way to initializea 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:-

    :-Here "Bean" is the nameof 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.

    Roseindia.net:-Here the element is used to declare the attributes and to pass the desired value to the property

    element, the element is used. Here the property name is "name"and its value is

    "Roseindia.net".

    Roseindia.net

    Rohini

    Software Development Company

    initMethod.xml

    Roseindia.net

    Rohini

    Software Development Company

    http://www.roseindia.net/spring/bean-init.shtml#%23http://www.roseindia.net/spring/bean-init.shtml#%23http://www.roseindia.net/spring/bean-init.shtml#%23http://www.roseindia.net/spring/bean-init.shtml#%23
  • 7/30/2019 Easy Spring Frmwrk

    29/32

    Here is the file named SimpleBean.java through which we are retrieving theproperties 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 org.springframework.beans.factory.BeanCreationException;import org.springframework.beans.factory.BeanFactory;

    import org.springframework.beans.factory.xml.XmlBeanFactory;import org.springframework.core.io.FileSystemResource;

    public class Bean {

    private static final String DEFAULT_NAME = "Girish"; private String name = null;

    private String address = null; private String type = null;

    public voidsetName(String name) { this.name = name;

    }public voidsetAddress(String address) {

    this.address = address; }

    public voidsetType(String type) { this.type = type;

    }

    public voidinit() { 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() {

    http://www.roseindia.net/spring/bean-init.shtml#%23http://www.roseindia.net/spring/bean-init.shtml#%23
  • 7/30/2019 Easy Spring Frmwrk

    30/32

    return "Name: " + name + "\nAddress: " + address + "\nType: " + type ; }

    public static voidmain(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 occuredin 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 springThis 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 usingjava file. Here in the file given below i.e. (context.xml) wehave declare the bean definition.

    Here "Bean" is the name of the bean class which would be further referred in the xmlfilewith the id "MyBean".

    :-Declares the property name of thebean and its value.

    http://www.roseindia.net/spring/bean-init.shtml#%23http://www.roseindia.net/spring/bean-init.shtml#%23http://www.roseindia.net/spring/bean-lifecycle-initializing.shtml#%23http://www.roseindia.net/spring/bean-lifecycle-initializing.shtml#%23http://www.roseindia.net/spring/bean-lifecycle-initializing.shtml#%23http://www.roseindia.net/spring/bean-lifecycle-initializing.shtml#%23http://www.roseindia.net/spring/bean-lifecycle-initializing.shtml#%23http://www.roseindia.net/spring/bean-init.shtml#%23http://www.roseindia.net/spring/bean-init.shtml#%23http://www.roseindia.net/spring/bean-lifecycle-initializing.shtml#%23http://www.roseindia.net/spring/bean-lifecycle-initializing.shtml#%23http://www.roseindia.net/spring/bean-lifecycle-initializing.shtml#%23
  • 7/30/2019 Easy Spring Frmwrk

    31/32

    context.xml

    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 toread bean definition from an XML document

    new ClassPathResource("context.xml"):-Creates a new ClassPathResource forClassLoader .Here the context.xml is the file which is to be loaded.

    class BeanSupport implements InitializingBean :-Here the InitializingBeaninterface is implemented by bean class. The use of this interface here is to do somepost processing actions when all the properties have been set by the Bean Factory..

    @Overridepublic String toString() { return String.format("%s : \"%s\"", t

    his.company, getValue());

    }

    Here the method toString() is overridden which is returning the the company nameand 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 voidmain(String[] args) throws Exception { XmlBeanFactory factory = new XmlBeanFactory(new

    ClassPathResource("context.xml"));

    System.out.println(factory.getBean("Mybean")); }

    http://www.roseindia.net/spring/bean-lifecycle-initializing.shtml#%23http://www.roseindia.net/spring/bean-lifecycle-initializing.shtml#%23http://www.roseindia.net/spring/bean-lifecycle-initializing.shtml#%23http://www.roseindia.net/spring/bean-lifecycle-initializing.shtml#%23
  • 7/30/2019 Easy Spring Frmwrk

    32/32

    }class Bean extends BeanSupport {

    private String company;

    public voidsetCompany(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 voidafterPropertiesSet() throws Exception { }

    public final voidsetValue(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

    loadBeanDefinitionsINFO: Loading XML bean definitions from class path resource

    [context.xml]

    Name : "Roseindia.net"BUILD SUCCESSFUL (total time: 1 second)

    Spring 3.0 Tutorials with example code