Friday, 20 June 2008

Spring in Action,Second Edition By Craig Walls With Ryan Breidenbach

Just now i completed reading Spring in Action,Second Edition By Craig Walls With Ryan Breidenbach

Book is great but personally i thought spring is cool when integrated in back-end layer rather than front-end layer.

I will suggest developers new to Spring Framework to follow this article which will provide us some basics regarding spring.

Below are few points i picked from the article.

1) Introduction To Spring
a) Spring is a light-weight framework for the development of enterprise-ready applications.
b) 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.
c) Spring framework can be used in modular fashion, it allows to use in parts

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

3) Spring Architecture

Spring is well-organized architecture consisting of seven modules. Modules in the Spring framework are:

Spring AOP
One of the key components of Spring is the AOP framework. AOP is used in Spring:

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

b) To allow users to implement custom aspects, complementing their use of OOP with AOP

Spring ORM
The ORM package is related to the database access. It provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis.

Spring Web
The Spring Web module is part of Spring’s web application development stack, which includes Spring MVC.

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.

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.

Spring Web MVC
This is the Module which provides the MVC implementations for the web applications.

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

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

5)Spring provides 'RmiProxyFactoryBean' to use the RMI service and 'RmiServiceExporter' to export any spring managed bean as a RMI service.

Spring also supports the server side of RMI. Here the service itself is written with spring and it is exposed as an RMI service. Here the bean is written as a simple JavaBean. Also we need not generate the stub and skeleton using 'rmic' command and manually add it to RMI registry. Instead of these traditional procedure 'RmiServiceExporter' is used to export any Spring managed bean as an RMI service. It wrapps the bean in an adapter class. The adapter class is then bound to RMI registry and the proxies request the service.

6) Dependency Injection proposes separating the implementation of an object and the construction of objects that depend on them.

There are three types of Dependency Injections.

Type 1 IOC also called Interface Injection In Type 1 IOC the injection is done though an interface. The interface will define the injection method and the implementation class has to implement this interface and provide concrete implementation for the injection method.

Type 2 IOC also called Setter Injection In Type 2 IOC the injection is done via a setter method. Type 2 IOC uses setter methods to get the dependent classes it needs.

Type 3 IOC also called Constructor Injection. In Type 3 IOC implementing class defines a constructor to get all its dependents. The dependent classes are defined in the constructor arguments.

7) How does Spring Work?

The idea is that beans follow the Dependency Injection pattern. Beans have information on the classes dependent on them. Beans define their own attributes within bean descriptors and also define the beans they depend on in the same descriptors. The Bean does not need to locate and instantiate these classes using service locators or JNDI calls. The Assembler (Spring Framework in this case) takes care of finding these classes based on the information provided in the descriptor and makes them available to the calling class. The service locator pattern does almost the same job, so why do we need another pattern to do it. The class that needs the dependent classes needs to tell the Service Locator as to which classes are required by it and moreover the responsibility of finding these classes and invoking them falls on the calling class. This makes the classes tightly coupled with each other making them difficult to unit test them separately. In the case of the Dependency Injection pattern the responsibility is shifted to the Assembler to load these classes. The assembler can make changes to the dependent classes by simply modifying the descriptor file. Martin Flower’s article in the resources shows the comparison between Dependency Injection and Service Locator with a good example.

8) The BeanFactory is a generic factory, which stores the information about all the Spring Beans and allows the user to instantiate beans and manage them. The ApplicationContext builds on top of the BeanFactory and inherits all the basic features of the Spring Framework.ApplicationContext provides additional features like Event management, internationalization support and resource management.

XMLBeanFactory is a BeanFactory implementation provided within the Spring Framework. The XMLBeanFactory can read BeanDefinitions from a XML file directly. The XMLBeanFactory validates the XML using a DTD file called beans.dtd and checks for inconsistencies in the XML.

The Bean, which is stored in the BeanFactory, is the actual class that would carry the logic for the bean. Spring does not define any standards on how the bean needs to be structured. Any J2EE complaint bean structure is acceptable to Spring. Unlike Struts and other frameworks the beans do not need to implement any special Spring interfaces to make them work in the Spring Framework. Depending upon the kind of Inversion required the bean might have to follow the rules of the corresponding Inversion Dependency pattern. Spring supports only Constructor based injection and setter based injection. So a bean that used constructor-based injection should have to define constructors accordingly. Spring recommends setter-based injection over constructor-based injection as multiple constructors can make the bean huge and unmanageable.

Beans can be deployed as singletons or as non-singletons. If a bean is defined as a singleton then only one instance of the bean is created by the BeanFactory and returned when a request for the bean is made.


Below are the points i wanted to share with readers from this book.

1) Spring is an open source framework, created by Rod Johnson and described in his book Expert One-on-One: J2EE Design and Development.Spring is a lightweight dependency injection and aspect-oriented container and framework.

2) Dependency Injection—Spring promotes loose coupling through a technique known as dependency injection (DI). When DI is applied, objects are passively given their dependencies instead of creating or looking for dependent objects for themselves. You can think of DI as JNDI in reverse—instead of an object looking up dependencies from a container, the container gives the dependencies to the object at instantiation without waiting to be asked.

Aspect-oriented—Spring comes with rich support for aspect-oriented programming (AOP) that enables cohesive development by separating application business logic from system services (such as auditing and transaction management). Application objects do what they’re supposed to do—perform business logic—and nothing more. They are not responsible for (or even aware of) other system concerns, such as logging or transactional support.

3) The key benefit of DI is loose coupling.

4) Most of Spring’s AOP configuration elements must be contained in .An aspect is made up of pointcuts (places where the aspect functionality will be applied) and advice (how to apply the functionality).

5) Bean factories (defined by the org.springframework.beans.factory.BeanFactory interface) are the simplest of containers, providing basic support for DI. Application contexts (defined by the org.springframework.context.ApplicationContext interface) build on the notion of a bean factory by providing application framework services, such as the ability to resolve textual messages from a properties file and
the ability to publish application events to interested event listeners.

There are several implementations of BeanFactory in Spring. But the one that is most commonly used is org.springframework.beans.factory.xml.XmlBean- Factory, which loads its beans based on the definitions contained in an XML file.

6) On the surface, an ApplicationContext is much the same as a BeanFactory.Both load bean definitions, wire beans together, and dispense beans upon request. But an ApplicationContext offers much more:

a) Application contexts provide a means for resolving text messages, including support for internationalization (I18N) of those messages.

b) Application contexts provide a generic way to load file resources, such as images.

c) Application contexts can publish events to beans that are registered as listeners.

7) Among the many implementations of ApplicationContext are three that are
commonly used:

a) ClassPathXmlApplicationContext—Loads a context definition from an XML file located in the classpath, treating context definition files as classpath resources.

b) FileSystemXmlApplicationContext—Loads a context definition from an XML file in the file system.

c) XmlWebApplicationContext—Loads context definitions from an XML file contained within a web application.


The difference between these uses of FileSystemXmlApplicationContext and ClassPathXmlApplicationContext is that FileSystemXmlApplicationContext will look for foo.xml in a specific location within the file system, whereas Class- PathXmlApplicationContext will look for foo.xml anywhere in the classpath
(including JAR files).

8) Another big difference between an application context and a bean factory is how singleton beans are loaded. A bean factory lazily loads all beans, deferring bean creation until the getBean() method is called. An application context is a bit smarter and preloads all singleton beans upon context startup. By preloading singleton beans, you ensure that they will be ready to use when needed—your application won’t have to wait for them to be created.

9) Life Cycle of a Bean is as follows:












StepDescription
InstantiateSpring instantiates the bean
Populate properties.Spring injects the bean’s properties.
Set bean nameIf the bean implements BeanNameAware, Spring passes the bean’s ID to setBeanName().
Set bean factoryIf the bean implements BeanFactoryAware, Spring passes the
bean factory to setBeanFactory().
Postprocess (before initialization)If there are any BeanPostProcessors, Spring calls their
postProcessBeforeInitialization() method.
Initialize beans.If the bean implements InitializingBean, its afterPropertiesSet() method will be called. If the bean has a custom init method declared, the specified initialization method will be called.
Postprocess(after initialization).If there are any BeanPostProcessors, Spring calls their
postProcessAfterInitialization() method.
Bean is ready to useAt this point the bean is ready to be used by the application and will
remain in the bean factory until it is no longer needed.
Destroy bean.If the bean implements DisposableBean, its destroy() method will be called.If the bean has a custom destroy-method declared, the specified method will be called.


10) Constructor or setter injection: how do you choose?

There are certain things that most people can agree upon: the fact that the sky is blue, that Michael Jordan is the greatest player to touch a basketball, and that Star Trek V should have never happened. And then there are those things that should never be discussed in polite company, such as politics, religion, and the
eternal “tastes great/less filling” debates.

Likewise, the choice between constructor injection and setter injection stirs up as much discourse as the arguments surrounding creamy versus crunchy peanut butter. Both have their merits and their weaknesses.

Which should you choose?

Those on the constructor-injection side of the debate will tell you that:

• Constructor injection enforces a strong dependency contract. In short, a bean cannot be instantiated without being given all of its dependencies. It is perfectly valid and ready to use upon instantiation. Of course, this assumes that the bean’s constructor has all of the bean’s dependencies in its parameter
list.

• Because all of the bean’s dependencies are set through its constructor,there’s no need for superfluous setter methods. This helps keep the lines of code at a minimum.

• By only allowing properties to be set through the constructor, you are, effectively,making those properties immutable, preventing accidental change in the course of application flow.

However, the setter injection-minded will be quick to respond with:

• If a bean has several dependencies, the constructor’s parameter list can be quite lengthy.

• If there are several ways to construct a valid object, it can be hard to come up with unique constructors, since constructor signatures vary only by the number and type of parameters.

• If a constructor takes two or more parameters of the same type, it may be difficult to determine what each parameter’s purpose is.

• Constructor injection does not lend itself readily to inheritance. A bean’s constructor will have to pass parameters to super() in order to set private properties in the parent object.

Fortunately, Spring doesn’t take sides in this debate and will let you choose the injection model that suits you best. In fact, you can even mix-and-match constructor and setter injection in the same application… or even in the same bean.

11) In a large application, however, all of this explicit wiring can result in a lot of XML. Rather than explicitly wiring all of your bean’s properties, you can have Spring automatically figure out how to wire beans together by setting the autowire property on each that you want Spring to autowire.

The four types of autowiring

Spring provides four flavors of autowiring:

byName—Attempts to find a bean in the container whose name (or ID) is the same as the name of the property being wired. If a matching bean is not found, the property will remain unwired.

byType—Attempts to find a single bean in the container whose type matches the type of the property being wired. If no matching bean is found,the property will not be wired. If more than one bean matches, an
org.springframework.beans.factory.UnsatisfiedDependencyException will be thrown.

constructor—Tries to match up one or more beans in the container with the parameters of one of the constructors of the bean being wired. In the event of ambiguous beans or ambiguous constructors, an org.springframework.beans.factory.UnsatisfiedDependencyException will be thrown.

autodetect—Attempts to autowire by constructor first and then using byType. Ambiguity is handled the same way as with constructor and byType wiring.

12) Autowiring by name

In Spring, everything is given a name. Bean properties are given names. And the beans that are wired into those properties are given names. If the name of a property happens to match the name of the bean that is to be wired into that property,that could serve as a hint to Spring that the bean should automatically be wired into the property.

For example, let’s revisit the kenny bean from section 2.3.2:






Here we’ve explicitly configured Kenny’s instrument property using .Just for the moment, let’s pretend that we declared the Saxophone as a with an id of instrument:



If this were the case, the id of the Saxophone bean would be the same as the name of the instrument property. Spring can take advantage of this to automatically configure Kenny’s instrument by setting the autowire property as follows:





13) By default, all Spring beans are singletons.

When declaring a in Spring, you have the option of declaring a scope for that bean. To force Spring to produce a new bean instance each time one is needed, you should declare the bean’s scope attribute to be prototype. For example, consider the following declaration of the saxophone bean:



14) Below are the Spring's bean scopes








ScopeWhat it does
singletonScopes the bean definition to a single instance per Spring container (default).
prototypeAllows a bean to be instantiated any number of times (once per use).
requestScopes a bean definition to an HTTP request. Only valid when used with a webcapable
Spring context (such as with Spring MVC).
sessionScopes a bean definition to an HTTP session. Only valid when used with a webcapable
Spring context (such as with Spring MVC).
global-sessionAScopes a bean definition to a global HTTP session. Only valid when used in a
portlet context.


Scoping is new to Spring 2.0. Prior to Spring 2.0, you would set a ’s singleton attribute to false to make it a prototype bean. The binary nature of the singleton attribute was quite limiting and didn’t allow for more interesting bean scopes, so the scope attribute was added. This is one area where backward compatibility is somewhat broken between Spring 1.x and Spring 2.0. If you’re using the Spring 2.0 DTD or XML schema when defining your context, you must use the scope attribute.But if you are still using the Spring 1.x DTD, you must use the singleton attribute.

15) To accommodate sub-beaning, the element provides two special attributes:

a) parent—Indicates the id of a that will be the parent of the with the parent attribute. The parent attribute is to what extends is to a Java class.

b) abstract—If set to true, indicates that the declaration is abstract. That is, it should never be instantiated by Spring.

16) In Java, children classes share a common base type that is determined by their parent bean. This means that there’s no way in Java for children classes to extend a common type to inherit properties and/or methods but not to inherit the common parent.

In Spring, however, sub-beans do not have to share a common parent type.Two s with completely different values in their class attributes can still share a common set of properties that are inherited from a parent bean.

17) Spring supports two forms of method injection:
a) Method replacement—Enables existing methods (abstract or concrete) to be replaced at runtime with new implementations.

b) Getter injection—Enables existing methods (abstract or concrete) to be replaced at runtime with a new implementation that returns a specific bean from the Spring context.

18) The @Configurable annotation does two things:
a) First, it indicates that Instrumentalist instances can be configured by Spring, even if they’re created outside of Spring.

b) It also associates the Instrumentalist class with a bean whose id is pianist.When Spring tries to configure an instance of Instrumentalist, it will look for a pianist bean to use as a template.

19) The configuration element is one of the many new configuration elements introduced in Spring 2.0. Its presence indicates to Spring that there are some beans that it will configure, even though they will be created elsewhere.

20) The BeanPostProcessor interface gives you two opportunities to alter a bean after it has been created and wired:

21) Spring’s HibernateTemplate provides an abstract layer over a Hibernate Session. HibernateTemplate’s main responsibility is to simplify the work of opening and closing Hibernate Sessions and to convert Hibernate-specific exceptions to one of the Spring ORM exceptions.

22) In the grand tradition of software development, an acronym has been created to
describe transactions: ACID. In short, ACID stands for:

a) Atomic—Transactions are made up of one or more activities bundled together as a single unit of work. Atomicity ensures that all the operations in the transaction happen or that none of them happen. If all the activities succeed, the transaction is a success. If any of the activities fail, the entire transaction fails and is rolled back.

b) Consistent—Once a transaction ends (whether successful or not), the system is left in a state that is consistent with the business that it models. The data
should not be corrupted with respect to reality.

c) Isolated—Transactions should allow multiple users to work with the same data, without each user’s work getting tangled up with the others. Therefore,transactions should be isolated from each other, preventing concurrent reads and writes to the same data from occurring. (Note that isolation typically involves locking rows and/or tables in a database.)

d) Durable—Once the transaction has completed, the results of the transaction should be made permanent so that they will survive any sort of system crash.This typically involves storing the results in a database or some other form of persistent storage.

About the Authors

Craig Walls is a software developer with over 12 years' experience and coauthor of XDoclet in Action. He is a zealous promoter of the Spring Framework, speaking frequently at local user groups and conferences and writing about Spring on his blog. When he's not slinging code, Craig spends as much time as he can with his wife, two daughters, 7 birds, 4 dogs, 2 cats, and an ever-fluctuating number of tropical fish. Craig lives in Denton, Texas.

An avid supporter of open source Java technologies, Ryan Breidenbach has developed Java web applications for the past seven years. He lives in Coppell, Texas.

Hope you enjoy reading this book

No comments: