A short note on Spring

Spring is a framework for J2EE. It has a number of layers including a MVC web layer, an AOP layer, DAO layer. One can leverage Spring’s DAO Support since Spring has a number of helper classes for JDBC and Hibernate that makes handling connections and Hibernate sessions easy.
Spring uses an Inversion Of Control (IoC) design which basically allows one to connect objects through descriptor configuration files instead of instantiating them through code. One creates an interface for both the service layer and the DAO layer. You can then create concrete implementations of these interfaces.
In the Spring configuration file one defines what concrete DAO class should be set on the service class. The concrete service object is also retrieved by making a call to the Spring “container”.
When the service object is instantiated, the container also instantiates the DAO object and sets it on the service object. What’s nice about this is that should the service class or DAO class ever change we need make changes only in the descriptor configuration files and not in the classes.
If the initial implementation of the DAO class was using Hibernate and for some reason we had to later use straight JDBC, then you create a new DAO object and change the Spring configuration without modifying the service layer at all.
Dependency lookup:
This is the EJB approach.
Dependency Injection:
Here the application objects are not responsible for looking up resources they depend upon. Instead IoC container configures the object externalizing resource lookup from application code. That is dependencies are injected into objects. The lookups are completely removed from application objects.

More useful information from this http://www.mydeveloperconnection.com/html/spring-hibernate-QnA.htm :

Dependency injection (DI) is a programming design pattern and architectural model, sometimes also referred to as inversion of control or IOC. Dependancy Injection describes the situation where one object uses a second object to provide a particular capacity. For example, being passed a database connection as an argument to the constructor instead of creating one internally. There are three common forms of dependency injection: setter-, constructor- and interface-based injection. Dependency injection is a way to achieve loose coupling. Inversion of control (IOC) relates to the way in which an object obtains references to its dependencies. The advantage of inversion of control is that it decouples objects from specific lookup mechanisms and implementations of the objects it depends on. As a result, more flexibility is obtained for production applications as well as for testing.

Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development. The Spring modules are built on top of the core container, which defines how beans are created, configured, and managed. Each of the modules (or components) that comprise the Spring framework can stand on its own or be implemented jointly with one or more of the others. The functionality of each component is as follows:

1. The core container: The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application’s configuration and dependency specification from the actual application code.

More about the 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 :

i. 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");

An example is shown in the standalone class AuthorSearchCreateBean.java http://cuppajavamattiz.com/2008/06/14/migrating-to-a-standalone-spring-hibernate-application/ .

authorSearchCreateBean.applicationContext = new org.springframework.context.support.ClassPathXmlApplicationContext("resources/mattiz.xml");
serviceManager = (DefaultServiceManager) applicationContext.getBean("mattiz.service.manager");

ii. 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");

iii. XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.

2. Spring context: The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality.

3. Spring AOP: The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module p
rovides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.
More on AOP
Aspect-oriented programming, or AOP is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. AOP and IOC are complementary technologies in that both apply a modular approach to complex problems in enterprise application development. In a typical object-oriented development approach you might implement logging functionality by putting logger statements in all your methods and Java classes. In an AOP approach you would instead modularize the logging services and apply them declaratively to the components that required logging. The advantage, of course, is that the Java class doesn’t need to know about the existence of the logging service or concern itself with any related code. As a result, application code written using Spring AOP is loosely coupled. The best tool to utilize AOP to its capability is AspectJ. However AspectJ works at the byte code level and you need to use AspectJ compiler to get the aop features built into your compiled code. Nevertheless AOP functionality is fully integrated into the Spring context for transaction management, logging, and various other features.

4. Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO’s JDBC-oriented exceptions comply to its generic DAO exception hierarchy.

5. Spring ORM: The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including Hibernate SQL Maps. All of these comply to Spring’s generic transaction and DAO exception hierarchies.

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 and JSF.

7. Spring MVC framework: The Model-View-Controller (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.

Advantages of Spring

a. Spring has layed architecture. Use what you need and leave you don’t need now.
b. Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continous integration and testability.
c. Dependency Injection and Inversion of Control Simplifies JDBC
d. Open source and no vendor lock-in.

e. Loose coupling – separates application configuration and dependency from business logic

f. Reduces boiler plate code.

g. Allows cross-cutting configurations at a modular level.

h. Can run on a web server instead of an application server.

e. Uses best practices from the Design patterns – Single responsibility principle, dependency injection, factory pattern, template pattern, singleton pattern and prototype pattern.

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.

About cuppajavamattiz
Matty Jacob - Avid technical blogger with interests in J2EE, Web Application Servers, Web frameworks, Open source libraries, Relational Databases, Web Services, Source control repositories, ETL, IDE Tools and related technologies.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: