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 declarative security through spring configuration file or class metadata while in EJB declarative security is configured through deployment descriptor. Spring provides proxying for RMI (special remoting technologies like Burlap) JAX-RPC & web-service while EJB provides container-managed remote method calls.Spring can offer declarative transaction like EJB. But spring provides declarative rollback behavior also ,for methods and exceptions Thus, while EJB is monolithic and attempts to do many things, some tasks fairly well and some others not so well, Spring uses ordinary Java beans only and through special techniques provides many of the functionalities of EJB, by integrating with a number of open-source technologies. Thereby, it gives the following advantages over EJB2. a) testing is easier. We do not need to start the EJB container , for testing. b) As Spring is based on the standard JavaBeans naming convention, programmers find it easy to work with. c) It makes use of AOP(Aspect-Oriented Programming) which is a very recent and useful paradigm., in addition to classic OOP and preserves the purity of OOP. d) It is flexible. Spring's goal is to be an entire Application Framework. Other popular framewoks like Struts, Tapestry, JSF etc., are very good web tier frameworks but when we use these framework, we have to provide additional framework to deal with enterprise tier that integrates well with these framework. Spring tries to alleviate this problem by providing a comprehensive framework, which includes a core bean container, an MVC framework, an AOP integration framework, a JDBC integration framework and an EJB integration framework.
It also provides integration modules for O/R mapping tools like Hibernate and JDO. Thus spring framework can be thought of as a layered architecture consisting of seven well defined modules.The function of each component is as follows:
1. Core Container: The core container provides the fundamental functionality of Spring. It's primary component is the 'BeanFactory', an implementation of the Factory pattern. The BeanFactory applies the IOC pattern to separate an application's configuration and dependency specification from the actual application code.
2. Spring Context/Application Context: The Spring context is a configuration file that provides context information to the Spring framework . The Spring context supplies enterprise services such as JNDI access, EJB integration, e-mail, internalization, validation, and scheduling functionality. 3. Spring AOP:(Aspect-Oriented) The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result we can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP we can incorporate declarative transaction management into our applications without relying on EJB components.The Spring AOP module also introduces metadata programming to Spring. Using this we can add annotation to the source code that instructs Spring on where and how to apply aspects. 4. Spring DAO: The Spring's JDBC and DAO abstraction layer offers a meaningful exception hierarchy for managing the databaase connection, exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of code that we need to write, such as opening and closing connections. This module also provide transaction management services for objects in a spring application. 5. Spring ORM: The Spring framework can be integrated to several ORM frameworks to provide Object Relational tool, including JDO, Hibernate, OJB and iBatis SQL Maps. 6. Spring Web module:The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts, JSF and webworks. The Web module also eases the tasks of handling multipart requests and binding request parameters to domain objects. 7. Spring MVC Framework:The MVC framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles and the generation of PDF and Excel Files. -------------------------------------------- I would venture to suggest that Spring will win sure acceptance among j2ee devcelopers , very soon because of its ready-made adapters for various hot web-tier and presentation technologies.! For example, there is a great varierty of technologies in the web-tier like MVC PATTERN, STRUTS, JSF, WEB-WORK, JSP, TAPESTRY,FREEMARKER etc. Developers are now puzzled and confused about the relative merits and demerits of all these. Once they choose a technology and start implementing and later want to change over to another technology, it is very difficult. But, as Spring offers modules for aall the above technologies, it is most often simply changing the configuraion file. With this approach, 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. Spring offers its own version of MVC architecture. It also offers adapters for Struts.
In the MVC adapter, it offers the following View choices.
JSP is default view template. 'InternalResouceViewResolver' can be used for this purpose. Spring can be integrated with other template solutions like Velocity, FreeMarker, tiles etc., Also Spring can be used to produce dynamic binary Excel spreadsheet, PDF documents etc.,
To configure the velocity engine 'VelocityConfigurer' bean is declared in spring configuration. The view resolver is configured by 'VelocityViewResolver' bean. To configure the FreeMarker engine 'FreeMarkerConfigurer' bean is declared in spring configuration. The view resolver is configured by 'FreeMarkerViewResolver' bean.
'TilesConfigurer' can used to used to load Tiles configuration file for rendering Tiles view. 'AbstractExcelView' is used to generate Excel SpreadSheet as views. 'AbstactPdfView' supports the creation of PDF as views. 'buildPdfDocument()' is used to create PDF decument. Similarly we have 'buildExcelDocument()' to create the excel document.
For delegation purpose, Spring provides 'DelegatingRequestProcessor' and to use the tiles 'DelegatingTilesRequestProcessor' is used. 'SpringTapestryEngine' is used for integrating Tapestry to Spring. 'FacesSpringVariableResolver' is used to resolve spring-managed beans in JSF. -----------------------------------------------------------------------------Next we shall see the main concepts of Spring, Inversion of Control (IoC) and Aspect Oriented Programming. Spring is based on dependency injection type of IoC . 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. A container is responsible for hooking it up. This concept is similar to 'Declarative Management'. IOC is a broad concept. the two main types are 1. Dependency Lookup: The container provides callbacks to components and a lookup context. The managed objects are responsible for their other lookups. 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. Here we need to use JNDI to look up other EJBs and resources. Because of this reason EJB is not branded as 'IOC framework'.There are some problems in this implementation. 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. 2. Dependency Injection: In this application objects is not responsible for looking up resources they depend on. Instead IoC container configures the object externalizing resource lookup from application code into the container. That is, dependencies are injected into objects. Thus lookups are completely removed from application objects and it can be used outside the container also. ---- In this method, the objects can be populated via Setter Injection (Java-Beans properties) or Constructor Injection (constructor arguments). Each method has its own advantage and disadvantage. Normally in all the java beans, we will use setter and getter method to set and get the value of property as follows public class namebean { String name; public void setName(String a) { name = a; } public String getName() { return name; } }
We will create an instance of the bean 'namebean' (say bean1) and set property as bean1.setName("tom"); Here in setter injection, we will set the property 'name' by using the
For constructor injection, we use constructor with parameters as shown below, public class namebean { String name; public namebean(String a) { name = a; } }
We will set the property 'name' while creatinf an instance of the bean 'namebean' as namebean bean1 = new namebean("tom"); Here we use the
To set properties that reference other beans , subelement of
The container is at the core of Spring Container. In manages the life cycle and configuration of application objects. 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. Spring should not, however, be confused with traditionally heavyweight EJB containers, which are often large. The Spring actually comes with two distinct containers: Bean Factories-defined by "org.springframework. beans.factory.BeanFactory" are the simplest containers, providing support for dependency injection. Application contexts - defined by "org.springframework.context.Application Context" provides application framework services. BEAN FACTORY: Bean factory is an implementation of the factory design pattern and its function is to create and dispense beans. As the bean factory knows about many objects within an application, it is able to create association between collaborating objects as they are instantiated. This removes the burden of configuration from the bean and the client.
There are several implementation of BeanFactory. The most useful one is "org.springframework.beans.factory.xml. XmlBeanFactory". It loads its beans based on the definition contained in an XML file. To create an XmlBeanFactory, pass a InputStream to the constructor. The resource will provide the XML to the factory. BeanFactory factory = new XmlBeanFactory(new FileInputStream("myBean.xml"));
This line tells the bean factory to read the bean definition from the XML file. The bean definition includes the description of beans and their properties. But the bean factory doesn't instantiate the bean yet. To retrieve a bean from a 'BeanFactory', the getBean() method is called. When getBean() method is called, factory will instantiate the bean and begin setting the bean's properties using dependency injection. myBean bean1 = (myBean)factory.getBean("myBean"); APPLICATION CONTEXT: While Bean Factory is used for simple applications, the Application Context is spring's more advanced container. Like 'BeanFactory' it can be used to load bean definitions, wire beans together and dispense beans upon request.
It also provide 1) a means for resolving text messages, including support for internationalization. 2) a generic way to load file resources. 3) events to beans that are registered as listeners.
Because of additional functionality, 'Application Context' is preferred over a BeanFactory. Only when the resource is scarce like mobile devices, 'BeanFactory' is used. The three commonly used implementation of 'Application Context' are
1. ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); 2. FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml"); 3. XmlWebApplicationContext : It loads context definition from an XML file contained within a web application. Spring is lightweight in terms of both size and overhead. The entire Spring framework can be distributed in a single JAR file that weighs just over 1.7 MB. And the processing overhead required by Spring is negligible. Also Spring is nonintrusive:(ie) objects in a Spring-enabled application typically have no dependencies on Spring-specific classes.
There are other lightweight containers like HiveMind, Avalon, PicoContainer etc., Avalon was one of the first IoC containers. Avalon mainly provides interface-dependent IoC. so, we much change our code in order to use a different container. This couples your code to a particular framework which is an undesirable feature.
PicoContainer is a minimal (very small size nearly 50k) lightweight container that provides IoC in the form of constructor and setter injection. By using PicoContainer we can only assemble components programmatically through PicoContainer's API. But it allows only one instance of any particular type to be present in the registry. Also PicoContainer is only a container. It does not offer various special features as spring like integration.
HiveMind is relatively new IoC container. Like PicoContainer, it focuses on wiring with support for both constructor and setter injections. It also allows us to define our configuration in an XML file. Like PicoContainer, HiveMind is only a container. It does not offer integration with other technology. Thus Spring makes it possible to configure and compose complex applications from simpler components. In Spring, application objects are composed declaratively, typically in an XML file. Spring also provides much infrastructure functionality like transaction management, persistence framework integration, etc., leaving the development of application logic to us. With this inroduction, we shall see a simple example in Spring in next article. SPRING ... A JUMP START
The Spring Framework comes in the form of ZIP file with the necessary jars, examples etc., The Spring framework can be downloaded from http://www.springframework.org. There will be two zip files one with dependencies and other without. The spring framework with dependencies is larger and includes all dependent libraries. Download Spring framework 1.2 without dependency and unzip on the hard disk as spring12
Inside the folder spring12 we can find 7 folders. The name and the contents of all the folders are given below, 1. dist: It contains various Spring distribution jar files. 2. docs: It contains general documentation and API javadocs. 3. mock: It contains mock JNDI contexts and a set of servlet API mock objects. 4. samples: It contains demo applications and skeletons. 5. src: It contains the Java source files for the framework. 6. test: It contains the Java source files for Spring's test suite. 7. tiger: It contains JDK1.5 examples and test suite.
Inside the "dist" directory, we can find all the jar files necessary for compiling and executing the program. The jar files and its contents are listed below: 1. spring.jar : It contains the entire Spring framework including everything in the other JAR files also. 2. spring-core.jar : It contains the core Spring container and its utilities. 3. spring-beans.jar : It contains the bean Spring container and JavaBeans support utilities. 4. spring-aop.jar : It contains Spring's AOP framework, source-level metadata support, AOP Alliance interfaces etc., 5. spring-context.jar : It contains application context, validation framework, JNDI, templating support and scheduling. 6. spring-dao.jar : It contains DAO support and transaction infrastructure. 7. spring-jdbc.jar : It contains the JDBC support. 8. spring-support.jar : It contains JMX support, JCA support, scheduling support, mail support and caching support. 9. spring-web.jar : It contains the web application context, multipart resolver, Struts support, JSF support and web utilities. 10. spring-webmvc.jar : It contains the framework servlets, web MVC framework, web controllers and web views. 11. spring-remoting.jar :It contains remoting support, EJB support and JMS support. 12. spring-orm.jar : It contains iBATIS SQL Maps support, Apache OJB support, TopLink support and JDO support. 13. spring-hibernate.jar : It contains Hibernate 2.1 support, Hibernate 3.x support. 14. spring-mock.jar : It contains JNDI mocks, Servlet API mocks and JUnit support. --------------------------------------------
Now we will run a greeter example in Spring.
f:\>md springdemo f:\>cd springdemo
As the entire Spring Framework is included in spring.jar. We use that to run our examples. Copy spring.jar from spring12\dist folder to the working folder. Also copy commons-logging.jar from tomcat41\server\lib to the working directory.
f:\springdemo>set path=c:\windows\command;g:\jdk1.5\bin (* Set path for jdk1.5 or jdk1.4.2 only. ) f:\springdemo>set classpath=f:\springdemo; f:\springdemo\spring.jar; f:\springdemo\commons-logging.jar For a typical Spring Application we need the following files 1. An interface that defines the functions. 2. An Implementation that contains properties, its setter and getter methods, functions etc., 3. A XML file called Spring configuration file. 4. Client program that uses the function.
Edit1. hello.java 2. helloimpl.java 3. hello.xml 4. helloclient.java //f:\springdemo\hello.java
public interface hello { public String sayhello(String a); } -------------------------------------------- //f:\springdemo\helloimpl.java public class helloimpl implements hello { private String greeting; public helloimpl() { } public helloimpl(String a) { greeting=a; } public String sayhello(String s) { return greeting+s; } public void setGreeting(String a) { greeting=a; } } -------------------------------------------- //f:\springdemo\hello.xml http://www.springframework.org/dtd/spring-beans.dtd">
To run: f:\springdemo>javac hello.java f:\springdemo>javac helloimpl.java f:\springdemo>javac helloclient.java f:\springdemo>java helloclient "sam" We will get the output as follows: please wait.. Aug 5, 2002 2:10:56 AM org.springframework. beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [hello.xml] Aug 5, 2002 2:10:57 AM org.springframework.beans.factory.support. AbstractBeanFactorygetBean INFO: Creating shared instance of singleton bean 'hello' Good Morning!...sam ------------------------------------
Thus we have run our first Spring program. Here helloimpl implements the hello interface. Although it is not necessary to hide the implementation behind an interface, it is recommended as a way to seperate implementation from interface. helloimpl has a single property greeting. This property can be set in two different ways: by property's setter method or by the constructor. The XML file hello.xml declares the instance of helloimpl.java in the spring container and configures its property greeting with the value 'Good Morning!...'
The root of the hello.xml file is the
Within the
The container instantiates the 'helloimpl' based on the XML definition as, helloimpl hello = new helloimpl(); helloimpl.setGreeting("Good Morning!...");
Similarly, greeting property may be set through the single argument constructor of 'helloimpl' as,
Now the container instantiates the 'helloimpl' based on the XML definition as,
helloimpl hello = new helloimpl("Good Morning...");
In the client program, 'BeanFactory' class is used which is the Spring container. Then the 'getBean()' method is called to get the reference to the 'hello'. With this reference, sayhello() method is called. ------------------------------------------
We can also use a frame client. The code is very much similar to console client except the GUI code. //f:\springdemo\helloframe.java import java.io.*; import java.awt.*; import org.springframework.beans.factory.*; import org.springframework.beans.factory.xml.*; import org.springframework.core.io.*; public class helloframe extends Frame { TextField text1; TextArea area1; Label label1; Button button1; public static void main(String args[]) { helloframe app = new helloframe(); app.setSize(700,500); app.setVisible(true); } helloframe() { setLayout(new FlowLayout()); setBackground(Color.green); label1=new Label("Type Name: "); text1=new TextField(25); area1=new TextArea(10,50); button1=new Button("Exit"); button1.setBackground(Color.red); add(label1); add(text1); add(area1); add(button1); } public boolean action (Event e,Object c) { if(e.target==text1) { try { area1.append("Please Wait..\n"); Resource res = new ClassPathResource("hello.xml"); BeanFactory factory = new XmlBeanFactory(res); hello bean1 = (hello)factory.getBean("hello"); String s = bean1.sayhello(text1.getText()); area1.append(s); } catch(Exception e1) {area1.append(""+e1);} } if(e.target==button1) { System.exit(0); } return true; } Then compile and run the frame client program. We will a textbox, a exit button and a text area. Type a name (say 'tom') in text area and press enter. 'Good Morning!... tom' will appear in the text area -------------------------------------------- Next we shall see how to run this program as a servlet. Consider Tomcat-5 is installed in g drive.First copy g:\spring12\spring.jar to g:\tomcat5\common\lib and start tomcat server.Then set classpath as shown below and edit the servletclient.java. f:\springdemo>set classpath=f:\springdemo; f:\springdemo\spring.jar; f:\springdemo\commons-logging.jar; g:\tomcat5\common\lib\servlet-api.jar //f:\springdemo\servletclient.java import java.io.*; import org.springframework.beans.factory.*; import org.springframework.beans.factory.xml.*; import org.springframework.core.io.*; import javax.servlet.*; import javax.servlet.http.*; public class servletclient extends HttpServlet { public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException { resp.setContentType("text/html"); PrintWriter out =resp.getWriter(); String a = req.getParameter("text1"); try { System.out.println("Please wait."); Resource res = new ClassPathResource("hello.xml"); System.out.println("Resource ok"); BeanFactory factory = new XmlBeanFactory(res); System.out.println("BeanFactory ok"); hello bean1 = (hello)factory.getBean("hello"); String s = bean1.sayhello(a); out.println(s); } catch(Exception e1) {System.out.println(""+e1);} } } -------------------------------------------- //f:\springdemo\servletclient.htm --------------------------------------------
Then compile the servlet and copy all the class files ie., hello.class, helloimpl.class, servletclient.class and the xml file hello.xml to g:\tomcat5\webapps\root\web-inf\classes. Copy html file servletclient.htm to g:\tomcat5\webapps\root. Add entry to web.xml file. Restart Tomcat server and open browser and type url as http://localhost:8080/servletclient.htm. We will get a text box and a button. Type a name (say 'tom') and click the 'submit' button. Good Morning!... tom will appear In the next article, we shall see how to contact the database from Spring. SPRING .... HITTING DATABASE Now we will move on to the main process of any enterprise application: Data Persistence. For this we have to initialize our data access framework, manage resources, handle various exceptions and if anything goes wrong, we must roll-back so as to save the existing data. Spring comes with a family of data access frameworks that integrates well will variety of data access technologies like JDBC, Java Data Objects and Object Relational Mapping (ORM) tools like Hibernate, OJB, iBatis etc., Many J2EE application servers and even web servers provide a 'dataSource' via Jndi name. To configure the spring bean with the Jndi name of our 'dataSource' and use its connection pooling facility 'JndiObjectFactoryBean' is used. When a DataSource is not present, we need a connection pooling bean that implements 'dataSource'. For this purpose we use 'dbcp.BasicDataSource' is used. By using this we can have a 'dataSource' with connection pooling independent of application server. To perform unit-tests in our data access code, spring comes with a very lightweight 'dataSource' implementation class: 'DriverManagerDataSource'. This class can be easily configured for unit tests as, DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); These properties can be configured in the spring configuration file also. ---------------------------------------------- Spring comes with its own data access framework. Spring separates the fixed and variant parts of data access process into two distinct classes : template and callback. Template manages the fixed part of our framework like data connection, managing resources, controlling transaction etc., while the Callback defines the things that are specific to our application like creating statements, binding parameters etc., The template class of Spring is 'JdbcTemplate'. A 'dataSource' is provided inside JdbcTemplate. An example of database connection using 'JdbcTemplate' is shown below. Here we are using 'MySql' database. The MySql database can be downloaded from http://www.mysql.com. Download mysql4.1 and MyODBC-3.51 (ODBC Connector) install these in the hard disk. For Mysql give a username('root') and a password ('sql'). Then start the 'My Sql Console Line Client' from programs and type the password. The prompt will be changed to mysql, mysql> show databases; Two databases will be present default: mysql and test. mysql> use test; We will get message as 'Database changed'. Next create table in test database as follows mysql> create table table1(name text, place text); We will get the message 'Query OK, 0 rows affected'. Now we have created a table in mysql database, set the path and classpath as before and edit the program -----f:\sprindemo\datacon.java import javax.sql.*; public interface datacon { public DataSource dbcon(); } ---------------------------------------- f:\sprindemo\dataconimpl.java import org.springframework.jdbc.core.*; import org.springframework.jdbc.datasource.*; import org.springframework.jdbc.object.*; import org.springframework.jdbc.support.*; import javax.sql.*; public class dataconimpl implements datacon { private DataSource dataSource; public void setDataSource(DataSource ds) { dataSource = ds; } public DataSource dbcon() { return dataSource; } } ---------------------------------------- f:\sprindemo\datacon.xml http://www.springframework.org/dtd/spring-beans.dtd">
No comments:
Post a Comment