You are on page 1of 46

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

-----------------------by Farihah Noushene B.E., --------------------------PART-I ----------------(PUBLISHED IN DEVELOPER IQ - September2005) Spring is an open-source application framework, introduced and developed in 2004. The main ideas were suggested by an experienced J2EE architect, Rod Johnson. He had earlier, written a book titled 'J2EE Develoment without using EJB' and had introduced the concept of Light-weight container. Primarily, his argument is that while EJB has its merits, it is not always necessary and suitable in all applications. Just as Hibernate attacks CMP as primitive ORM technology, Spring attacks EJB as unduly complicated and not susceptible to unit-testing. Instead of EJB, Spring suggests that we make use of ordinary Java beans, with some slight modifications, to get all the supposed advantages of EJB environment. Thus, Spring is posed as an alternative to EJB essentially. However, as a concession to the existing EJB investments, Spring is designed to operate with EJB if required. Much of the philosophy and approach of Spring framework, however, predates , the latest EJB vesrion (ie) EJB-3, about to arrive shortly. It is said that EJB-3 has absorbed a number of new ideas suggested by Spring and some more, to answer the criticisms. There is a debate going on in the Java community about Spring and EJB-3. Spring is not a Persistence technolgy but a framework which allows plug in of other such technologies. But EJB-3 is primarily focussed on Persistence Technology and has now incorporated Hibernate, the best ORM todate.Talks are going on to incorpotrate another equally nice ORM Technology known as JDO, which provides for Object Database also. Moreoveer, EJB-3 's Attribute-Orientaed Meta tags, help in vastly reducing the size of XML lines. Some have complained that Spring is still too dependent on XML files. In this tutorial, any reference to EJB, is only to EJB-2.My aim in presenting this tutorial is not to advocate the choice of either Spring or EJB-3, a topic still being devbated by experts but to share my perception with our readers.

In spring, we can make use of plain Java Beans to achieve things that were previously possible with EJB only. The main aim of Spring is to simplify the J2EE development and testing. EJB has been around since 1988 and is an established standard and specification in Enterprise world. Though there have been numerous Open-source Java technologies recently, no other technology has claimed to be superior to EJB, in its total features. Rod Johnson, in his book, critices a number of features in EJB. Significantly, he has also spoken approvingly of some features of EJB and has recommended its use in some special circumstances. EJB is a standard with wide Enterprise-level Industry support.It has been deployed in thousands of successful applications around the world. The EJB specification is a fixed target and so tool-developers are able to develop wizards, which can make ejb development quick and easy. There are many vendors for EJB application server like IBM (Web-Sphere), BEA (Weblogic), Oracle (JDeveloper) etc. To quote from another book on Spring ("Spring in Action" - Craig Walls-Manning press) " EJB is complex ", as the author put it nicely, "not for just being complex'. It is complex because it attempts to provide solutions for complex problems". EJB is developed mainly for the remote transaction and distributed objects. But a number of enterprise projects do not have this level of complexity and still use EJBs and even the simple application becomes complex. In such cases Spring claims to be an alternative. Since Spring comes with rich support to enterprise level services, it claims to be an alternative to EJB It is worthwhile to begin with a comparison of EJB-2 and Spring, in some main features. The main advantages of EJB are : a) Transaction Management b) Declarative Transaction support c) Persistence ( CMP & BMP) d) Declarative Security e) Distributed Computing (Container managed RPC) Spring does not attempt to do everything by itself but supports the best of breed technologies for each of these requirements. For example, instead of CMP & BMP, it supports several persistence technologies like JDO, Hibernate and OJB. These ORM toools are far more capable than the implementation in CMP.To simplify JDBC coding, there are tools like iBatis and Spring supports iBatis also. Spring makes use of Acegi, an open-source Security framework and provides

an MVC framework. d) It is flexible. Spring tries to alleviate this problem by providing a comprehensive framework.. an implementation of the Factory pattern. Core Container: The core container provides the fundamental functionality of Spring. It's primary component is the 'BeanFactory'. e-mail. EJB integration. while EJB is monolithic and attempts to do many things. We do not need to start the EJB container . Spring provides proxying for RMI (special remoting technologies like Burlap) JAXRPC & web-service while EJB provides container-managed remote method calls. some tasks fairly well and some others not so well. c) It makes use of AOP(Aspect-Oriented Programming) which is a very recent and useful paradigm. The function of each component is as follows: 1. programmers find it easy to work with. The Spring context supplies enterprise services such as JNDI access. in addition to classic OOP and preserves the purity of OOP. Tapestry. But spring provides declarative rollback behavior also . Thus spring framework can be thought of as a layered architecture consisting of seven well defined modules. Other popular framewoks like Struts. it gives the following advantages over EJB2. Spring can offer declarative transaction like EJB. a JDBC integration framework and an EJB integration framework. It also provides integration modules for O/R mapping tools like Hibernate and JDO. Spring's goal is to be an entire Application Framework. an AOP integration framework.. Spring Context/Application Context: The Spring context is a configuration file that provides context information to the Spring framework . internalization. are very good web tier frameworks but when we use these framework.declarative security through spring configuration file or class metadata while in EJB declarative security is configured through deployment descriptor. by integrating with a number of open-source technologies.for methods and exceptions Thus. a) testing is easier. Thereby. b) As Spring is based on the standard JavaBeans naming convention. Spring uses ordinary Java beans only and through special techniques provides many of the functionalities of EJB. The BeanFactory applies the IOC pattern to separate an application's configuration and dependency specification from the actual application code. and scheduling . validation. JSF etc. we have to provide additional framework to deal with enterprise tier that integrates well with these framework. for testing. which includes a core bean container. 2.

Spring AOP:(Aspect-Oriented) The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework. Spring ORM: The Spring framework can be integrated to several ORM frameworks to provide Object Relational tool. 4. providing contexts for Web-based applications. the Spring framework supports integration with Jakarta Struts. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP. JSP. STRUTS. Developers are now puzzled and confused about the relative merits and demerits of all these. such as opening and closing connections. Using this we can add annotation to the source code that instructs Spring on where and how to apply aspects. JSF. through its configuration management feature. As a result we can easily AOP-enable any object managed by the Spring framework. exception handling and error messages thrown by different database vendors. 5. very soon because of its ready-made adapters for various hot web-tier and presentation technologies. Once they choose a technology and start implementing and later want to change . As a result. 3. there is a great varierty of technologies in the web-tier like MVC PATTERN. JSF and webworks. Spring Web module: The Web context module builds on top of the application context module. OJB and iBatis SQL Maps. Tiles and the generation of PDF and Excel Files. The Spring AOP module provides transaction management services for objects in any Spring-based application. The exception hierarchy simplifies error handling and greatly reduces the amount of code that we need to write. including JDO.functionality. The Web module also eases the tasks of handling multipart requests and binding request parameters to domain objects. 6. The Spring AOP module also introduces metadata programming to Spring.FREEMARKER etc. Spring DAO: The Spring's JDBC and DAO abstraction layer offers a meaningful exception hierarchy for managing the databaase connection.! For example. With Spring AOP we can incorporate declarative transaction management into our applications without relying on EJB components. 7. Spring MVC Framework: The MVC framework is a full-featured MVC implementation for building Web applications. Hibernate. WEB-WORK. TAPESTRY. This module also provide transaction management services for objects in a spring application. Velocity. -------------------------------------------I would venture to suggest that Spring will win sure acceptance among j2ee devcelopers .

With this approach. Spring can be integrated with other template solutions like Velocity. To configure the velocity engine 'VelocityConfigurer' bean is declared in spring configuration. 'InternalResouceViewResolver' can be used for this purpose. it is even possible for a development team to try and test a given task in all the above forms and see the effect and performance before deciding the choice. To configure the FreeMarker engine 'FreeMarkerConfigurer' bean is declared in spring configuration. the two main types are 1. We don't directly connect our components and services together in code but describe which services are needed by which components in a configuration file. tiles etc. it is very difficult. 'AbstactPdfView' supports the creation of PDF as views. But. it offers the following View choices. FreeMarker.over to another technology. as Spring offers modules for aall the above technologies. it is most often simply changing the configuraion file. This concept is similar to 'Declarative Management'. Inversion of Control (IoC) and Aspect Oriented Programming. In the MVC adapter. Here we need to use JNDI to look up other EJBs and . This is the EJB Approach. The Inversion of Control is limited to the Container involved callback methods that the code can use to obtain resources.. For delegation purpose. Spring is based on dependency injection type of IoC . The view resolver is configured by 'FreeMarkerViewResolver' bean. ----------------------------------------------------------------------------Next we shall see the main concepts of Spring. The view resolver is configured by 'VelocityViewResolver' bean. 'FacesSpringVariableResolver' is used to resolve spring-managed beans in JSF. A container is responsible for hooking it up. 'buildPdfDocument()' is used to create PDF decument. JSP is default view template. IOC is a broad concept. Spring provides 'DelegatingRequestProcessor' and to use the tiles 'DelegatingTilesRequestProcessor' is used. Spring offers its own version of MVC architecture. 'SpringTapestryEngine' is used for integrating Tapestry to Spring. Dependency Lookup: The container provides callbacks to components and a lookup context. PDF documents etc. Similarly we have 'buildExcelDocument()' to create the excel document. The managed objects are responsible for their other lookups. It also offers adapters for Struts. 'AbstractExcelView' is used to generate Excel SpreadSheet as views. 'TilesConfigurer' can used to used to load Tiles configuration file for rendering Tiles view. Also Spring can be used to produce dynamic binary Excel spreadsheet..

} } . Each method has its own advantage and disadvantage. } public String getName() { return name. That is. Thus lookups are completely removed from application objects and it can be used outside the container also. the objects can be populated via Setter Injection (Java-Beans properties) or Constructor Injection (constructor arguments). 2. dependencies are injected into objects.resources. Instead IoC container configures the object externalizing resource lookup from application code into the container. ---In this method. we will use setter and getter method to set and get the value of property as follows public class namebean { String name. The class needs a application server environment as it is dependent on JNDI and it is hard to test as we need to provide a dummy JNDI contest for testing purpose. Dependency Injection: In this application objects is not responsible for looking up resources they depend on.There are some problems in this implementation. Normally in all the java beans. public void setName(String a) { name = a. Because of this reason EJB is not branded as 'IOC framework'.

we will set the property 'name' by using the <property> subelement of <bean> tag in spring configuration file as showm below. public namebean(String a) { name = a.setName("tom"). <bean id="bean1" class="namebean"> <property name="name" > <value>tom</value> </property> </bean> The subelement <value> sets the 'name' property by calling the set method as setName("tom"). For constructor injection. we use constructor with parameters as shown below. Here in setter injection. This process is called setter injection. public class namebean { String name.We will create an instance of the bean 'namebean' (say bean1) and set property as bean1. } } .

Here we use the <constructor-arg> element to set the the property by constructor injection as <bean id="bean1" class="namebean"> <constructor-arg> <value>My Bean Value</value> </constructor-arg> </bean> To set properties that reference other beans <ref>.. security etc. must be included in the program. System are composed of several components each responsible for a specific piece of functionality. These system services are commonly refered to as 'cross-cutting concerns' as they tend to cut across multiple components in a system. subelement of <property> is used as shown below. transaction management. AOP makes it possible to modularize and separate these services and then apply them declaratively to the .We will set the property 'name' while creatinf an instance of the bean 'namebean' as namebean bean1 = new namebean("tom"). the system service like logging. <bean id="bean1" class="bean1impl"> <property name="game"> <ref bean="bean2"/> </property> </bean> <bean id="bean2" class="bean2impl" /> Aspect-Oriented Programming --------------------------Aspect Oriented programming is a new programming technique that promotes separation of concerns within the system. Whatever may be the core function of the program.

In manages the life cycle and configuration of application objects. In spring. APPLICATION CONTEXT: While Bean Factory is used for simple applications. however. The most useful one is "org. aspects are wired into objects in the spring XML file in the same way as JavaBean.components and we can focus on our own specific concerns.Application Context" provides application framework services. There are several implementation of BeanFactory. factory will instantiate the bean and begin setting the bean's properties using dependency injection. Application contexts . To retrieve a bean from a 'BeanFactory'.getBean("myBean"). It also provide . This removes the burden of configuration from the bean and the client. XmlBeanFactory". pass a InputStream to the constructor. The bean definition includes the description of beans and their properties.springframework.defined by "org.BeanFactory" are the simplest containers. be confused with traditionally heavyweight EJB containers. We can configure how each of our beans should be created either to create a single instance of bean or produce a new instance every time and how they should be associated with each other.xml.springframework. which are often large.context. BeanFactory factory = new XmlBeanFactory(new FileInputStream("myBean. The Spring actually comes with two distinct containers: Bean Factories-defined by "org.xml")). BEAN FACTORY: Bean factory is an implementation of the factory design pattern and its function is to create and dispense beans. Like 'BeanFactory' it can be used to load bean definitions. the getBean() method is called. This line tells the bean factory to read the bean definition from the XML file. wire beans together and dispense beans upon request. it is able to create association between collaborating objects as they are instantiated. When getBean() method is called. The resource will provide the XML to the factory.springframework.factory. beans.beans. Spring should not. But the bean factory doesn't instantiate the bean yet. To create an XmlBeanFactory. As the bean factory knows about many objects within an application. the Application Context is spring's more advanced container. providing support for dependency injection.factory. This process is known as 'Weaving'. It loads its beans based on the definition contained in an XML file. myBean bean1 = (myBean)factory. ---------------------------------------The container is at the core of Spring Container.

The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext("bean. Spring is lightweight in terms of both size and overhead. It does not offer various special features as spring like integration. we much change our code in order to use a different container. typically in an XML file.xml"). Avalon mainly provides interfacedependent IoC.7 MB. HiveMind is relatively new IoC container. FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. treating context definitions as classpath resources. Thus Spring makes it possible to configure and compose complex applications from simpler components. Also PicoContainer is only a container. And the processing overhead required by Spring is negligible. There are other lightweight containers like HiveMind.xml"). It also allows us to define our configuration in an XML file. including support for internationalization. ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath. 'BeanFactory' is used. 2) a generic way to load file resources. Like PicoContainer. 2. The entire Spring framework can be distributed in a single JAR file that weighs just over 1. Like PicoContainer. In Spring. Avalon. The application context is loaded from the application's classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext("bean. This couples your code to a particular framework which is an undesirable feature.. application objects are composed declaratively. XmlWebApplicationContext : It loads context definition from an XML file contained within a web application. persistence . It does not offer integration with other technology. The three commonly used implementation of 'Application Context' are 1. But it allows only one instance of any particular type to be present in the registry. it focuses on wiring with support for both constructor and setter injections. Also Spring is nonintrusive:(ie) objects in a Spring-enabled application typically have no dependencies on Spring-specific classes. PicoContainer etc. HiveMind is only a container. Because of additional functionality. Only when the resource is scarce like mobile devices. 3) events to beans that are registered as listeners. so.1) a means for resolving text messages. Spring also provides much infrastructure functionality like transaction management. By using PicoContainer we can only assemble components programmatically through PicoContainer's API. PicoContainer is a minimal (very small size nearly 50k) lightweight container that provides IoC in the form of constructor and setter injection. Avalon was one of the first IoC containers. 3. 'Application Context' is preferred over a BeanFactory.

Inside the "dist" directory. 2. ------------------------------------------BOOKS FOR REFERENCE: 1. we can find all the jar files necessary for compiling and executing the program.September2005) The Spring Framework comes in the form of ZIP file with the necessary jars. With this inroduction. dist: It contains various Spring distribution jar files. docs: It contains general documentation and API javadocs. 4. samples: It contains demo applications and skeletons. 1. 3.jar : It contains the bean Spring container and JavaBeans support utilities. 2.. test: It contains the Java source files for Spring's test suite.. ------------------------PART-II ----------------(PUBLISHED IN DEVELOPER IQ . The jar files and its contents are listed below: 1.jar : It contains the entire Spring framework including everything in the other JAR files also. The spring framework with dependencies is larger and includes all dependent libraries. Download Spring framework 1. There will be two zip files one with dependencies and other without. 6.Craig Walls and Ryan Breidenbach. examples etc. tiger: It contains JDK1. leaving the development of application logic to us.2 without dependency and unzip on the hard disk as spring12 Inside the folder spring12 we can find 7 folders. spring. 3. spring-core.springframework. The Spring framework can be downloaded from http://www.'J2EE Development without EJB' . ..'Spring in Action' . 7.. spring-beans. etc. we shall see a simple example in Spring in next article. 2. : It contains the core Spring container and its utilities.framework integration. mock: It contains mock JNDI contexts and a set of servlet API mock objects. A JUMP START ----------------------by Farihah Noushene B.Rod Johnson SPRING .E. src: It contains the Java source files for the framework. The name and the contents of all the folders are given below..5 examples and test suite.

An Implementation that contains properties. spring-orm.jar : It contains iBATIS SQL Maps support. 8. scheduling support. mail support and caching support. functions etc.5 or jdk1.jar : It contains the framework servlets.x support.4. its setter and getter methods. 5.2 only. spring-aop. Struts support.5\bin (* Set path for jdk1. spring-webmvc.jar :It contains remoting support. 6. 7.4. Apache OJB support. spring-mock.jar. spring-context. spring-dao. 12. JCA support. templating support and scheduling. TopLink support and JDO support.jar : It contains Spring's AOP framework.jar : It contains DAO support and transaction infrastructure. ) f:\springdemo>set classpath=f:\springdemo. JNDI. An interface that defines the functions. spring-hibernate. Hibernate 3. 11. Also copy commons-logging. Servlet API mocks and JUnit support.1 support. spring-remoting. 9.jar.. 3. 13. f:\>md springdemo f:\>cd springdemo As the entire Spring Framework is included in spring. JSF support and web utilities. 2. web MVC framework. -------------------------------------------Now we will run a greeter example in Spring. . validation framework. spring-support.g:\jdk1. spring-web. f:\springdemo\spring.jar : It contains JMX support.jar from tomcat41\server\lib to the working directory. AOP Alliance interfaces etc.jar from spring12\dist folder to the working folder. 14. 10.. multipart resolver. spring-jdbc.jar : It contains application context. source-level metadata support.jar : It contains JNDI mocks.jar : It contains the web application context. Copy spring.jar For a typical Spring Application we need the following files 1.jar : It contains the JDBC support. f:\springdemo>set path=c:\windows\command. web controllers and web views. A XML file called Spring configuration file.jar : It contains Hibernate 2. f:\springdemo\commons-logging. We use that to run our examples. EJB support and JMS support.

} -------------------------------------------//f:\springdemo\ //f:\springdemo\ 2. hello. public helloimpl() { } public helloimpl(String a) { greeting=a. } . } public String sayhello(String s) { return 3. helloimpl. hello. Edit public interface hello { public String sayhello(String a). Client program that uses the public class helloimpl implements hello { private String greeting. helloclient.xml 4.

factory.*.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.beans.*. import org.beans..public void setGreeting(String a) { greeting=a.</value> </property> </bean> </beans> -------------------------------------------//f:\springdemo\helloclient.factory. .xml <?xml version="1.springframework..*"> <beans> <bean id="hello" class="helloimpl"> <property name="greeting"> <value>Good Morning!.java import java. import org. } } -------------------------------------------//f:\springdemo\ beans.springframework.out.xml") f:\springdemo>java helloclient "sam" We will get the output as follows: please wait.println(""+e1). Resource res = new ClassPathResource("hello.import org.out.println(s)..println("please Wait. String s = bean1. BeanFactory factory = new XmlBeanFactory(res).sayhello(args[0]).*. } } } ------------------------------------------To run: f:\springdemo>javac hello.getBean("hello").java f:\springdemo>javac f:\springdemo>javac helloimpl. } catch(Exception e1) { System. Aug 5.factory. hello bean1 = (hello)factory. 2002 2:10:56 AM org.springframework.xml.core."). public class helloclient { public static void main(String args[]) throws Exception { try { System.XmlBeanDefinitionReader loadBeanDefinitions .

This property can be set in two different ways: by property's setter method or by the constructor. Here we have given 'Good Morning!. we’re telling the Spring container to call setGreeting() while setting the property.' as the value. Here. By using <property>... The container instantiates the 'helloimpl' based on the XML definition as.").sam -----------------------------------Thus we have run our first Spring program.xml declares the instance of helloimpl. which is the root element of any Spring configuration file. Similarly. Although it is not necessary to hide the implementation behind an interface. helloimpl has a single property greeting. greeting property may be set through the single argument constructor of 'helloimpl' as. The value of the greeting is defined within the <value> element. Here helloimpl implements the hello in the spring container and configures its property greeting with the value 'Good Morning!. the <property> element is used to set the property. helloimpl hello = new helloimpl().INFO: Loading XML bean definitions from class path resource [hello. in this case the greeting property. beans..xml file is the <beans> it is recommended as a way to seperate implementation from interface...</value> </constructor-arg> </bean> . Within the <bean> element. The <bean> element is used to tell the Spring container about the class and how it should be configured.setGreeting("Good Morning!... AbstractBeanFactorygetBean INFO: Creating shared instance of singleton bean 'hello' Good Morning!.' The root of the hello. 2002 2:10:57 AM org. The XML file hello.xml] Aug 5. <bean id="hello" class="helloimpl"> <constructor-arg> <value>Good Morning!. helloimpl...factory. the id attribute takes the interface name and the class attribute specifies the bean’s fully qualified class name.

*. button1.").springframework. public static void main(String args[]) { helloframe app = new helloframe(). sayhello() method is called.beans.core.springframework. //f:\springdemo\helloframe.Now the container instantiates the 'helloimpl' based on the XML definition area1. The code is very much similar to console client except the GUI code. 'BeanFactory' class is used which is the Spring container.*.awt. Then the 'getBean()' method is called to get the reference to the 'hello'.factory. label1. import java. helloimpl hello = new helloimpl("Good public class helloframe extends Frame { TextField TextArea Label Button import java. -----------------------------------------We can also use a frame client.*. In the client program.springframework.xml..*.beans. import org. .factory. import org.. import org.*. With this reference.

add(label1). area1=new TextArea(10. label1=new Label("Type Name: "). button1=new Button("Exit"). add(button1).50).green). add(text1).red). } helloframe() { setLayout(new FlowLayout()). button1.500). text1=new TextField(25).setVisible(true). setBackground( { try .app. app.setBackground(Color.setSize(700. } public boolean action (Event e.Object c) { if(e. add(area1).

append(""+e1).getText()). Type a name (say 'tom') in text area and press enter.append(s). . We will a textbox. 'Good Morning!. a exit button and a text area.} } if(e.\n").getBean("hello"). hello bean1 = (hello)factory. Consider Tomcat-5 is installed in g drive. Resource res = new ClassPathResource("hello. String s = bean1...jar to g:\tomcat5\common\lib and start tomcat server.exit(0).xml"). } Then compile and run the frame client program. First copy g:\spring12\spring. } return true. } catch(Exception e1) {area1.append("Please { System..{ area1. area1.sayhello(text1. BeanFactory factory = new XmlBeanFactory(res). tom' will appear in the text area -------------------------------------------Next we shall see how to run this program as a servlet.

import javax.beans.factory. f:\springdemo\spring.factory. import java. public class servletclient extends HttpServlet { public void doPost(HttpServletRequest req.Then set classpath as shown below and edit the servletclient.servlet. import org. g:\tomcat5\common\lib\ PrintWriter out =resp. import org. f:\springdemo>set classpath=f:\springdemo. import { resp.springframework.jar //f:\springdemo\servletclient.setContentType("text/html"). String a = req.springframework. import javax.*.core.servlet. f:\springdemo\commons-logging.*.jar.springframework.getParameter("text1").*.*.*.xml.getWriter().HttpServletResponse resp) throws ServletException.beans.jar.*.

htm .out. String s = bean1. } catch(Exception e1) {System. hello bean1 = (hello)factory. out. Resource res = new ClassPathResource("hello.println("Resource ok"). BeanFactory factory = new XmlBeanFactory(res).println("Please wait. System.out.getBean("hello"). System.xml").println(s).out.sayhello(a).").} } } -------------------------------------------//f:\springdemo\servletclient.println("BeanFactory ok").println(""+e1).try { System.out.

.htm. Copy html file servletclient...xml file.<html> <body> <form method=post action="http://localhost:8080/ servlet/servletclient"> <input type=text name="text1"> <input type=submit> </form> </body> </html> -------------------------------------------Then compile the servlet and copy all the class files ie. HITTING DATABASE by Farihah Noushene B.. we shall see how to contact the database from Spring.E. Good Morning!.class. SPRING .class and the xml file hello.xml to g:\tomcat5\webapps\root\webinf\classes. Restart Tomcat server and open browser and type url as http://localhost:8080/servletclient..htm to g:\tomcat5\webapps\root.. hello. servletclient. PART-III . Add entry to web.class. Type a name (say 'tom') and click the 'submit' button. helloimpl. We will get a text box and a button.. tom will appear In the next article.

we must roll-back so as to save the existing data. while the Callback defines the things that are specific to our application like creating statements. controlling transaction etc. To configure the spring bean with the Jndi name of our 'dataSource' and use its connection pooling facility 'JndiObjectFactoryBean' is used.. .(PUBLISHED IN DEVELOPER IQ . Java Data Objects and Object Relational Mapping (ORM) tools like Hibernate. dataSource. we need a connection pooling bean that implements 'dataSource'. This class can be easily configured for unit tests as. To perform unit-tests in our data access code. dataSource. Spring separates the fixed and variant parts of data access process into two distinct classes : template and callback. OJB. By using this we can have a 'dataSource' with connection pooling independent of application server. A 'dataSource' is provided inside JdbcTemplate.setUsername(username). For this we have to initialize our data access framework.setPassword(password). The template class of Spring is 'JdbcTemplate'. dataSource.setUrl(url). manage resources.. spring comes with a very lightweight 'dataSource' implementation class: 'DriverManagerDataSource'.September2005) Now we will move on to the main process of any enterprise application: Data Persistence. binding parameters etc. Many J2EE application servers and even web servers provide a 'dataSource' via Jndi name. For this purpose we use 'dbcp. dataSource. ---------------------------------------------Spring comes with its own data access framework. DriverManagerDataSource dataSource = new DriverManagerDataSource(). These properties can be configured in the spring configuration file also.setDriverClassName(driver).. handle various exceptions and if anything goes wrong. iBatis etc. Spring comes with a family of data access frameworks that integrates well will variety of data access technologies like JDBC.BasicDataSource' is used. Template manages the fixed part of our framework like data connection. When a DataSource is not present. managing resources.

The MySql database can be downloaded from http://www. We will get message as 'Database changed'.1 and MyODBC-3. .An example of database connection using 'JdbcTemplate' is shown import import org.51 (ODBC Connector) install these in the hard disk.*. Then start the 'My Sql Console Line Client' from programs and type the password.core. For Mysql give a username('root') and a password ('sql'). public interface datacon { public DataSource dbcon().com.datasource. set the path and classpath as before and edit the program ----f:\sprindemo\datacon. mysql> show databases. Here we are using 'MySql' database. mysql> use test. Two databases will be present default: mysql and test.mysql. place text). Now we have created a table in mysql database. We will get the message 'Query OK.jdbc. Download mysql4. Next create table in test database as follows mysql> create table table1(name text. 0 rows affected'. import org. } ---------------------------------------f:\sprindemo\dataconimpl.springframework. The prompt will be changed to mysql.sql.*.*.jdbc.

xml <?xml version="1. } public DataSource dbcon() { return import org.jdbc.import"> <beans> <bean id="dataSource" .object.sql. import javax.*.*.*. } } ---------------------------------------f:\sprindemo\datacon. public class dataconimpl implements datacon { private DataSource dataSource. public void setDataSource(DataSource ds) { dataSource = ds.jdbc.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.

jdbc.springframework.jdbc.JdbcOdbcDriver</value> </property> <property name="url"> <value>jdbc:odbc:test</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>sql</value> </property> </bean> <bean id="datacon" class="dataconimpl"> <property name="dataSource"> <ref local="dataSource"/> </property> </bean> </beans> ---------------------------------------f:\sprindemo\springservlet.odbc.class="org.DriverManagerDataSource"> <property name="driverClassName"> <value> .

import org. import org.core.*.factory.springframework.beans.*.jdbc. String a = import javax.sql.jdbc.*. import org.*.*.springframework.servlet.servlet.datasource.http.factory.sql.object. import javax.jdbc.springframework. String b = req.springframework.getParameter("text2").springframework. PrintWriter out =*.util.jdbc.xml.import java.*.beans.getParameter("text1").IOException { resp.core.*.*. import org.getWriter(). public class springservlet extends HttpServlet { public void doPost(HttpServletRequest req. import javax. import org. import java. .*. import org.setContentType("text/html").*.*.io.springframework. import org.HttpServletResponse resp) throws ServletException.springframework. import java.*.

println("Record Added"). } if(d. } if(d.dbcon().getParameter("combo1")..equals("delete")) { JdbcTemplate jt = new JdbcTemplate(ds).. String d = req. BeanFactory factory = new XmlBeanFactory(res). out. Resource res = new ClassPathResource("datacon. out. try { System. if(d.equals("add")) { JdbcTemplate jt = new JdbcTemplate(ds).String c = req.execute("insert into table1 values('"+a+"'.equals("find")) .out.println("Record Deleted").xml").getBean("datacon").").'"+b+"') "). jt.println("Wait. jt.execute("delete from table1 where name='"+a+"' "). datacon bean1 = (datacon)factory. DataSource ds=bean1.getParameter("combo2").

list1=jt. } if(c.queryForList("select * from table1 where name='"+a+"'"). . JdbcTemplate jt = new JdbcTemplate(ds).place='"+b+"'where table1.iterator().next().execute("update table1 set table1. Iterator i=list1.{ List list1. jt.println(ob. out. } } if('"+a+"' ").equals("name")) { JdbcTemplate jt = new JdbcTemplate(ds).equals("place")) { JdbcTemplate jt = new JdbcTemplate(ds).toString()). while(i.equals("update")) { if(c.hasNext()) { Object ob = i.

} out.htm <html> <body bgcolor="pink"> <form method=post action="http://localhost:8080/ servlet/springservlet"> Name Place : <input type=text name="text1"> <br><br> : <input type=text name="text2"> <br><br> Criterion : <select name="combo1" size=1> <option value="name">Name .execute("update table1 set table1.jt.println(""+e1).} } } ---------------------------------------f:\sprindemo\springservlet.out.println("Record Updated"). } } catch(Exception e1) {'"+a+"'where'"+b+"' ").

We will get message as 'Record Added' ---------------------------------------Spring provides integration for many of the ORM frameworks like Hibernate. dataconimpl.xml to g:\tomcat5\webapps\root\web-inf\classes. To access the data with 'HibernateTemplate' . 'LocalSessionFactoryBean' is used for this purpose and its properties 'hibernateProperties'. and copy all the class files and the xml file datacon.htm.xml file.<option value="place">Place </select> <br><br> <select name="combo2" size=1> <option value="add">Add <option value="delete">Remove <option value="find">Find <option value="update">Update </select> <br><br> <input type=submit> </form> </body> </html> The deployment procedure is same as before compile the all the files datacon. Add entry to web. 'mappingResources' and 'mappingDirectoryLocation' are set. We will get a two textboxes. Apache OJB and iBATIS SQL Maps. Like Spring's DAO framework. an instance of 'SessionFactory' is needed. Copy the html file to g:\tomcat5\webapps\ here we have 'HibernateTemplate' to create an object of 'SessionFactory'. two comboboxes and a 'submit' button. select 'add' from combobox and click 'submit' button. Type name and place in textboxes. For mapping the hibernate resources. Start Tomcat server and open browser and type url as http://localhost:8080/ and springservlet.

. Remote Method Invocation (RMI) 2. In the next article we shall see how to use a RMI service in Spring and how to export any Spring managed bean as RMI. To access the data 'execute(SQLMapClientCallback)' method is used.'execute(HibernateCallback)' method is used. Also 'JDOTemplate' to create an object of 'PersistenceManagerFactory'. we have to configure a 'SQLMapClient' by using 'SQLMapClientFactoryBean' and its properties 'configLocation' and 'dataSource' are set. Hessian 3.. It can be configured by using 'LocalPersistenceManagerFactoryBean'.September2005) Spring supports remoting for six different RPC models: 1. HTTP invoker . For iBATIS. Burlap 4. Similar to the 'SessionFactory' of hibernate. To access the data with 'JDOTemplate' 'execute(JDOCallback)' method is used. PART-IV (PUBLISHED IN DEVELOPER IQ . --------------------------------------------- SPRING ..E. Here also we have 'SQLMapClientTemplate'. The only property that we need to change to integrate Spring with OJB is 'ConnectionFactoryClass' and it is done by using 'LocalDataSourceConnectionFactory'. JDO has 'PersistenceManager Factory'. REMOTING by Farihah Noushene B.

For exporting beans as HTTP invoker services. 'LocalStatelessSessionProxyFactoryBean' is used to access the EJB in the same container(local) and another one is 'SimpleRemoteStatelessSessionProxyFactoryBean' which is used to access the remote EJBs. This is accomplished by using a proxy factory bean that enable us to wire remote services into the properties of our beans as if they were local objects. AbstractJmsMessageDrivenBean to develop MDBs that accept messages from JMS sources. The client makes calls to the proxy to provide the service and the proxy calls the remote service on behalf of the client. For all the above models spring provides service exporter classes that exports Java Beans as remote service. JAX-RPC In all the models. EJB 6. . Spring provides two proxy factory beans to access the Enterprise Java Beans. AbstractMessageDrivenBean to develop MDBs that accept sources other than JMS. 'JaxRpcPostProxyFactoryBean' is used to wire a web service into the spring application. Spring provides 'RmiProxyFactoryBean' to use the RMI service and 'RmiServiceExporter' to export any spring managed bean as a RMI service. Spring's 'HessianProxyFactory Bean' is used.To access an HTTP invoker service 'HttpInvokerProxyFactoryBean' can be used. They are 1. 4. AbstractStstefulSessionBean to develop stateful session bean. services are configured into the application through spring configuration file as spring managed beans. For wiring a Hessian based service to Spring client. 'HttpInvokerServiceExporter' is used . AbstractStatelessSessionBean to develop stateless session bean. To export a Hessian Service 'HessianServiceExporter' is used and similarly for wiring a Burlap service 'BurlapProxyFactoryBean' is used and 'BurlapServiceExporter' is used to export a burlap service.5. 2. 3. Spring does not provide any EJB Service Exporter and it provides four abstract support classes to make the development of Spring enabled EJB.

For using the service the implementation code is wired to the RMI using the following code. Spring simplifies the RMI by providing a 'proxy factory bean' that enables us to wire the RMI services into spring application as if they were local beans.rmi. It is declared spring configuration file under the <bean> tag as follows. But developing and accessing RMI services involves various steps and also have lookups which makes the code hard to test.RmiProxyFactoryBean"> <property name="serviceUrl"> <value>rmi://${hostname}/service1</value> </property> <property name="serviceInterface"> <value>service1</value> </property> </bean> The url of the RMI service is set through the 'serviceUrl' property.1. Spring's 'RmiProxyFactoryBean' is a factory bean that creates a proxy to RMI service.-------------------------------------------Now we shall see how to wire other RMI services into spring application and also how to export our own service. Spring also provides a remote exporter that converts our 'spring managed beans' into RMI services.remoting. The 'serviceInterface' property specifies the interface that the service implements and only through that the client invokes methods on the service. <bean id="serviceimpl" class="serviceimpl"> <property name="service1"> . <bean id="service1" class="org. Remote Method Invocation (RMI) Model: RMI was first introduced in JDK 1.springframework. import java.rmi. public class rmserverimpl extends UnicastRemoteObject implements rmserver { public static void main(String args[]) { try { .java import java.*. } ---------------------------------------------//f:\springdemo\rmserverimpl. public interface rmserver extends Remote { String getresult(String s) throws RemoteException.rmi. //f:\springdemo\rmserver.*. Next edit the RMI service. import java.*.<ref bean="service1"/> </property> </bean> ------------------------------------------First set the path and classpath as before.

Naming. System.println(""+e1).springframework. } } ---------------------------------------------//f:\springdemo\rmserver."+a.out.rebind("rmserver".out.println("constructor ok").0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" " spring-beans.out.ob).} } public rmserverimpl() throws RemoteException { System... } public String getresult(String a) throws RemoteException { return "Hai.println("ready").rmserverimpl ob = new rmserverimpl().dtd"> .xml <?xml version="1. } catch(Exception e1) {System.

factory. import org.RmiProxyFactoryBean"> <property name="serviceUrl"> <value>rmi://localhost/rmserver</value> </property> <property name="serviceInterface"> <value>rmserver</value> </property> </bean> <bean id="rmserverimpl" class="rmserverimpl"> <property name="rmserver"> <ref bean="rmserver"/> </property> </bean> </beans> --------------------------------------------//f:\springdemo\rmspring. import org.*.springframework.rmi.springframework.factory.beans.springframework.xml.*. .*. import*.java import java.beans.core.remoting.<beans> <bean id="rmserver" class="org.springframework.

").getBean("rmserver"). rmserver bean1 = (rmserver) f:\springdemo>javac rmserverimpl..} } } --------------------------------------To run: f:\springdemo>javac rmserver. Resource res = new ClassPathResource("rmi. System.out.xml").out. } catch(Exception e1) {System.println(""+e1).getresult(args[0]). BeanFactory factory = new XmlBeanFactory(res).println("Wait.out. String r=bean1.public class rmspring { public static void main(String args[]) { try { f:\springdemo>rmic rmserverimpl (To create stub and skeleton) .println(r).

. <bean class="org. .RmiServiceExporter"> <property name="service1"> <ref bean="service1"/> </property> <property name="serviceName"> <value>service1</value> </property> <property name="serviceInterface"> ... Also we need not generate the stub and skeleton using 'rmic' command and manually add it to RMI registry. It wrapps the bean in an adapter class...rmi. Here the bean is written as a simple JavaBean. sam Here we have removed the 'lookup' code in the client side. Hai. Instead of these traditional procedure 'RmiServiceExporter' is used to export any Spring managed bean as an RMI f:\springdemo>start rmiregistry (a blank window will appear) f:\springdemo>java rmserverimpl Open another Window and run the client code by giving the argument f:\springdemo>java rmspring "sam" We will get the output as: Wait.remoting.. The adapter class is then bound to RMI registry and the proxies request the service.. Here the service itself is written with spring and it is exposed as an RMI service.f:\springdemo>javac rmspring. ----------------------------------------------------------------Spring also supports the server side of RMI.

//f:\springdemo\rmservice. There is no need of 'serviceUrl' here First set the path and classpath as before.out.println("ready").out. } -----------------------------------------//f:\springdemo\rmserviceimpl. } public rmserviceimpl() { public class rmserviceimpl implements { public static void main(String args[]) { System. Next edit the service.<value>service1</value> </property> </bean> The 'serviceName property' indicates the name of service and 'serviceInterface' specifies the interface implemented by the public interface rmservice { String getresult(String s).println("constructor ok"). } rmservice .

remoting.dtd"> <beans> <bean class="org.springframework. } } -----------------------------------------//f:\springdemo\rmservice.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.RmiServiceExporter"> <property name="service"> <value>rmservice</value> </property> <property name="serviceName"> <value>service1</value> </property> <property name="serviceInterface"> <value>rmservice</value> </property> </bean> .org/dtd/ spring-beans.public String getresult(String a) { return "Hai"+a.springframework.rmi.xml <?xml version="1.

core.out.getBean("rmservice").out.beans. String s = bean1..springframework. Resource res = new ClassPathResource("rmservice.<bean id="rmservice" class="rmserviceimpl"> </bean> </beans> -----------------------------------------//f:\springdemo\rmserviceclient.beans.").springframework.xml")*.springframework.*.getresult(args[0]).*. import org.println("factory created").out. import org. class rmserviceclient { public static void main(String args[]) { try { System. . BeanFactory factory = new XmlBeanFactory(res). import org.*.io. rmservice bean1 = (rmservice)factory. System.println("Wait.factory.println(s) import java. System.

Aug f:\springdemo>javac rmserviceimpl.factory.xml] Aug 12. 2002 10:55:07 PM f:\springdemo>javac rmserviceclient. support.} catch(Exception e1) {System.AbstractBeanFactory getBean f:\springdemo>java rmsserviceclient We will get Output as: Wait. xml.beans.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource[rmservice.out.} } } --------------------------------------To run: f:\springdemo>javac rmservice. 2002 10:55:07 PM org.beans.println(""+e1).springframework.springframework.

-------------------------------------- . Also we can direcly run the client.rmi.. Also there is no need to run the RMI registry. No run to run 'rmserverimpl' first.Remote' method and 'RemoteException' is not thrown by the methods.INFO: Creating shared instance of singleton bean 'rmservice' constructor ok Hai..sam Here the service interface doesn't extend the 'java. There is no binding in the implementation code.