Tuesday, 8 July 2008

Professional Java Development with the Spring Framework

Just now i finished reading Professional Java Development with the Spring Framework Book By Rod Johnson, Juergen Hoeller, Alef Arendsen, Thomas Risberg, Colin Sampaleanu.

Nice book written by nice authors.

I skipped 4th Chapter Asjectj with Spring as i have no idea what is aspectj hence i thought to read about Asjectj programming and come back to spring implementation with Aspectj later.

I wanted to share few important points i found from this book.

1) Spring is an application framework. Unlike single-tier frameworks such as Struts or Hibernate, Spring aims to help structure whole applications in a consistent, productive manner, pulling together best-of-breed single-tier frameworks to create a coherent architecture.

2) Following are the key Spring modules:

a) Inversion of Control container: The core "container" Spring provides, enabling sophisticated configuration management for POJOs. The Spring IoC container can manage fine or coarse- grained POJOs (object granularity is a matter for developers, not the framework), and work with other parts of Spring to offer services as well as configuration management.

b) Aspect-Oriented Programming (AOP) framework: AOP enables behavior that would otherwise be scattered through different methods to be modularized in a single place. Spring uses AOP under the hood to deliver important out-of-the-box services such as declarative transaction management. Spring AOP can also be used to implement custom code that would otherwise be scattered between application classes.

c) Data access abstraction: Spring encourages a consistent architectural approach to data access,and provides a unique and powerful abstraction to implement it. Spring provides a rich hierarchy of data access exceptions, independent of any particular persistence product. It also provides a range of helper services for leading persistence APIs, enabling developers to write persistence framework–agnostic data access interfaces and implement them with the tool of their choice.

d) JDBC simplification: Spring provides an abstraction layer over JDBC that is significantly simpler and less error-prone to use than JDBC when you need to use SQL-based access to relational databases.

e) Transaction management: Spring provides a transaction abstraction that can sit over JTA "global" transactions (managed by an application server) or "local" transactions using the JDBC, Hibernate,JDO, or another data access API. This abstraction provides a consistent programming model in a wide range of environments and is the basis for Spring's declarative and programmatic transaction
management.

f) MVC web framework: Spring provides a request-based MVC web framework. Its use of shared instances of multithreaded "controllers" is similar to the approach of Struts, but Spring's web framework is more flexible, and integrates seamlessly with the Spring IoC container. All other Spring features can also be used with other web frameworks such as Struts or JSF.

g) Simplification for working with JNDI, JTA, and other J2EE APIs: Spring can help remove the need for much of the verbose, boilerplate code that "doesn't do anything." With Spring, you can continue to use JNDI or EJB, if you want, but you'll never need to write another JNDI lookup. Instead,simple configuration can result in Spring performing the lookup on your behalf, guaranteeing that resources such as JNDI contexts are closed even in the event of an exception. The dividend is that you get to focus on writing code that you need to write because it relates to your business domain.

h) Lightweight remoting: Spring provides support for POJO-based remoting over a range of protocols,including RMI, IIOP, and Hessian, Burlap, and other web services protocols.

i) JMS support: Spring provides support for sending and receiving JMS messages in a much simpler way than provided through standard J2EE.

j) JMX support: Spring supports JMX management of application objects it configures.

k) Support for a comprehensive testing strategy for application developers: Spring not only helps to facilitate good design, allowing effective unit testing, but provides a comprehensive solution for integration testing outside an application server.

3) The key Spring values can be summarized as follows:

a) Spring is a non-invasive framework.
b) Spring provides a consistent programming model, usable in any environment.
c) Spring aims to promote code reuse.
d) Spring aims to facilitate Object Oriented design in J2EE applications.
e) Spring aims to facilitate good programming practice, such as programming to interfaces,rather than classes.
f) Spring promotes pluggability.
g) Spring facilitates the extraction of configuration values from Java code into XML or properties files.
h) Spring is designed so that applications using it are as easy as possible to test.
i) Spring is consistent.
j) Spring promotes architectural choice.
k) Spring does not reinvent the wheel.

4) Inversion of Control is best understood through the term the "Hollywood Principle," which basically means "Don't call me, I'll call you."

Dependency Injection is a form of push configuration; the container "pushes" dependencies into application objects at runtime. This is the opposite of traditional pull configuration, in which the application object "pulls" dependencies from its environment. Thus, Dependency Injection objects never load custom properties or go to a database to load configuration — the framework is wholly responsible for actually reading configuration.

5) Spring calls the classes using a callback approach based on templates. This is another form of Inversion of Control; the application developer can work with native API constructs such as JDBC Connections and Statements without needing to handle API-specific exceptions (which will automatically be translated into Spring's exception hierarchy) or close resources (which will automatically be released by the framework).

6) Inversion of Control and Dependency Injection
Software code is normally broken up into logical components or services that interact with each other. In Java, these components are usually instances of Java classes, or objects. Each object must use or work with other objects in order to do its job. For an object A, it can be said that the other objects that object A deals with are its dependencies. Inversion of Control refers to the generally desirable architectural pattern of having an outside entity (the container in this case) wire together objects, such that objects are given their dependencies by the container, instead of directly instantiating them themselves.

7) Method Injection, the final form of dependency injection we are going to look at, is the most rarely used. In this form, the container is responsible for implementing methods at runtime. For example, an object might define a protected abstract method, and the container might implement it at runtime to return an object resulting from a container lookup. The aim of method injection is, again, to avoid dependencies on the
container APIs, and reduce coupling.

8) Deciding Between Setter Injection and Constructor Injection

a) Using JavaBean properties generally makes it easier to handle default or optional values, in the case that not all values are actually needed. In the constructor case, this usually leads to multiple constructor variants, with one calling another internally. The many variations or long argument lists can become very verbose and unmanageable.

b) JavaBean properties (as long as they are not private) are automatically inherited by subclasses, while constructors are never inherited. The latter limitation often leads to the need to create relatively boilerplate constructors in subclasses, which call superclass constructors. Most IDEs, however, do now include code completion aids that make creation of either constructors or JavaBean properties
fairly effortless.

c) JavaBean properties are arguably better at being self-documenting than constructor arguments, at the source level. When adding JavaDocs, properties require less work to document as there is no duplication.

d) At runtime, JavaBean properties may be used for matching based on name because properties have names visible by reflection. However, in a compiled class file, constructor argument names are not retained, so that automatic matching based on name is not possible.

e) JavaBean properties allow getting the current state (as well as setting it) if a getter method is provided. This is useful in a number of situations, such as when the state needs to be stored elsewhere.

f) The JavaBeans PropertyEditor mechanism exists for performing automatic type conversion when needed. This is in fact used and supported by Spring.

g) JavaBean properties can be mutable because a setter method can be called multiple times. This allows changing a dependency if the use case actually supports it. Dependencies passed in via constructors cannot be mutable unless also exposed as properties. If, on the other hand, complete immutability is required, then Constructor Injection allows you to also explicitly declare the field set
from a constructor argument as final, whereas the best that a setter method can do is throw an exception if it is called more than once; there is no way to make the field storing the value from the setter method final, so that other class code may not modify it.

h) Constructor arguments make it easier to ensure a valid object is constructed because all required values can be declared and thus must be passed in, and the class is free to use them in the order they are needed, in the process of initialization. With JavaBean properties, there is the possibility that
some properties have not been set before the object is used, resulting in an invalid state. Additionally,with JavaBean properties, there is no way to specify and enforce that setters must be called in a certain order, which may mean that initialization may need to take place after property setting, via the use of an init method. If used, such an init method can also verify that all needed properties have
been set. Spring can automatically call any declared initialization method after all properties have been set, or alternately beans may implement the InitializingBean interface, which declares an afterPropertiesSet() method that will automatically be called.

i) When there are only a few constructors, this can sometimes be less verbose than many JavaBean property accessor methods. Most IDEs, however, do now include code completion aids, which make creation of either constructors or JavaBean properties fairly effortless.

Generally, the Spring team prefers the use of setter injection over constructor injection for most cases in practice, although this decision should not be a hard and fast one.

9) The basic IoC container in Spring is called the bean factory.Any bean factory allows the configuration and wiring together of objects using dependency injection, in a consistent and workable fashion.

10) The Application Context

It is important to stress that an application context is a bean factory, with the
org.springframework.context.ApplicationContext interface being a subclass of BeanFactory.

Why the distinction? It comes down mostly to increased functionality, and usage style:

a) General framework-oriented usage style: Certain operations on the container or beans in the container,which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context. This includes the automatic recognition and usage of special bean post-processors and bean factory post-processors, to be described shortly. Additionally, a number of Spring Framework
facilities exist to automatically load application contexts, for example in the Web MVC layer, such that bean factories will mostly be created by user code, but application contexts will mostly be used in a declarative fashion, being created by framework code. Of course, in both cases, most of the user code will be
managed by the container, and won't know anything about the container at all.

b) MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.

c) Support for application and framework events: The context is able to fire framework or application events to registered listeners.

d) ResourceLoader support: Spring's Resource interface is a flexible generic abstraction for handling lowlevel resources. An application context itself is a ResourceLoader, hence provides an application with access to deployment-specific Resource instances.

In almost all cases you are better off using an application context because you will get more features at no real cost.You may be wondering when it's most appropriate to create and use a bean factory versus an application context. In almost all cases you are better off using an application context because you will get more features at no real cost. The main exception is perhaps something like an applet where every last byte of memory used (or transferred) is significant, and a bean factory will save some memory because you can use the Spring library package, which brings in only bean factory functionality, without bringing in
application context functionality.


11) Creating and loading an XML-configured bean factory is just as simple. The easiest mechanism is to use Spring's Resource abstraction for getting at a classpath resource:

ClassPathResource res =new ClassPathResource("org/springframework/prospering/beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);

or

FilesystemResource res = new FilesystemResource("/some/file/path/beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);


But we can also just use an InputStream:

InputStream is = new FileInputStream("/some/file/path/beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(is);


12) An important aspect of the bean lifecycle is whether the container treats it as a singleton or not. Singleton beans, the default, are created only once by the container.A non-singleton, or prototype bean as it is also called, may be specified by setting the singleton attribute to false.

13) Specifying Bean Dependencies, Detailed

From the XML DTD, we can see that a number of elements are allowed inside a property or constructorarg
element. Each is used to specify some sort of value for a property or constructor argument:
(bean | ref | idref | list | set | map | props | value | null)

The ref element is used to set the value of a property or constructor argument to be a reference to another
bean from the factory, or from a parent factory:





The local, bean, or parent attributes are mutually exclusive, and must be the ID of the other bean. When using the local attribute, the XML parser is able to verify at parse time that the specified bean exists.However, because this relies on XML's IDREF mechanism, that bean must be in the same XML file as the reference, and its definition must use the id attribute to specify the ID being referred to, not name. When the bean attribute is used, the specified bean may be located in the same or another XML fragment that is used to build up the factory definition, or alternately in any parent factory of the current factory. However, Spring itself (not the XML parser) will validate that the specified bean exists, and this will happen only when that dependency actually needs to be resolved, not at factory load time. The much less frequently used parent attribute specifies that the target bean must come from a parent factory to the current one. This may be used in the rare cases when there is a name conflict between a bean in the current factory and a parent factory.

14) Constructor Argument Matching

As a general rule, you should almost always use the optional index or type attributes with constructorarg elements you specify.

15) Application Events

All events to be published and received with the event framework must extend the ApplicationEvent class, which is itself a subclass of the standard java.util.EventObject class.In order to automatically receive events, a bean must simply implement the ApplicationListener interface and be deployed into the application context. It will be recognized by the context, and receive all events that are published through the context:

16) Definitions from Properties Files

An alternative declarative definition format is the use of Java Properties files, and their close cousins,ResourceBundles. The Properties definition format is not as expressive as XML; there are a number of container capabilities that cannot be expressed using this format, including constructor-injection,method-injection, nested beans, or setting of complex collection types. However, for simple basic bean
definitions with Setter Injection, it's fairly concise, and it might also be useful in an environment where it's not desirable to bring in an XML parser. An example might be an applet using only basic BeanFactory functionality, and trying to keep code size and memory use down. One Spring class that uses this format itself is ResourceBundleViewResolver, part of Spring's web MVC layer. The use there is well-suited because view definitions are fairly simple, with no nesting needed, and the class is able to take advantage
of ResourceBundles to load views appropriate to various locales.

17) Declarative Transactions
Declarative transactions provide a very attractive alternative to the programmatic solutions. Your code can now be transaction agnostic and you can allow a framework to demarcate the transactions. Not having to include transaction management in your code makes your code much more readable and easier to maintain. It also allows you to switch transaction strategy or implementation without changing your code.

The EJB specification defines a number of transaction attributes that you specify in the deployment descriptor. The EJB transaction attributes for container-managed transaction demarcation are:

REQUIRED: This means that the method must participate in a transaction. A new transaction will be started if one is not already active.

REQUIRES NEW: A new transaction will always be started for this method. If there is an active transaction for the calling component, then that transaction is suspended until this method has completed.

NOT SUPPORTED: The method will not take part in any transactions. If there is one active in the calling component, then it is suspended while this method is processing. The suspended transaction is resumed once this method has completed.

SUPPORTS: There is no requirement that this method should be executed in a transaction. If one is already started, then this method will take part in that transaction.

MANDATORY: The calling component must already have an active transaction that this method will take part in.

NEVER: This method is not participating in a transaction and it is also required that there is not an active transaction for the calling component.

18) Spring's RMI support consists of the following main classes:

org.springframework.remoting.rmi.RmiProxyFactoryBean: Proxy factory for Springcompliant proxies that communicate with backend RMI services. To be defined in a Spring bean factory or application context, exposing the proxy object for references (through the FactoryBean mechanism).
Proxies will either throw RMI's RemoteException or Spring's generic RemoteAccessException in
case of remote invocation failure, depending on the type of service interface used.

org.springframework.remoting.rmi.RmiServiceExporter: Exporter that registers a given
service — either a traditional RMI service or a plain Java object — with the RMI registry. Can take any existing Spring-managed bean and expose it under a given RMI name in the registry, allowing the target bean to be fully configured and wired via Spring. Creates an in-process RMI registry if none is found at the specified port. The same target bean can easily be exported through other protocols (such as HTTP
invoker) at the same time.

19) RMI is the traditional option for Java-to-Java remoting. Spring enhances it through the RMI invoker mechanism, which allows it to use a plain Java business interface on top of the RMI backend infrastructure.

However, consider HTTP invoker as a direct alternative. Both are binary and roughly
equivalent in terms of efficiency. The serialization mechanism is the same: standard Java serialization. The main difference is that HTTP invoker is more convenient. It can easily go through firewalls, does not require a registry, and does not need to reconnect in case of a server restart.

Nevertheless, RMI's level of setup and maintenance is often acceptable, in particular with Spring's auto-reconnect feature (see the following section). Note that as with HTTP invoker,the class versions at both ends have to be compatible — a consequence of using Java serialization.

20) Asynchronous messaging is important in many enterprise applications. Spring provides support for consuming JMS messages, which both simplifies the programming model (compared to direct use of the JMS API) and provides a consistent basis for access to advanced features such as dynamic destinations.

JmsTemplate uses the JMS 1.1 API, and the subclass JmsTemplate102 uses the JMS 1.0 API.

Boolean property PubSubDomain is used to configure the JmsTemplate with knowledge of what messaging category is being used, point-to-point or Pub/Sub. This is important when using the JmsTemplate102. The default value of this property is false, indicating that the point-to-point domain will be used. This flag has no effect on send operations for the 1.1 implementation since the 1.0 API is agnostic to the messaging category.

The JmsTemplate increases the level of abstraction in using JMS by providing overloaded convertAndSend and receiveAndConvert methods, which represent the message data type as a Java object instead of a javax.jms.Message. These methods convert between Java objects and JMS messages by delegating the conversion process to an instance of the MessageConverter interface.

21) Like many other MVC frameworks, Spring's Web MVC framework is built around a generic servlet known as a Dispatcher Servlet or Front Controller.

22) The MVC architectural pattern aims to divide the layer implementing interactions with users into three different kinds of objects:

Model objects represent data: for example, the orders a user has placed, or information about a user's account.

View objects are responsible for displaying the data represented by the model: for instance, in a table,list, or form.

Controllers are objects responding to the actions a user takes, such as a form submission or a link being clicked. Controllers are responsible for updating the data represented by the model or taking other appropriate measures related to the user's action. This might for example involve delegating a request to the business tier that in turn will process an order.

23) Spring uses a view resolution strategy involving logical view names. Views are identified by name, keeping controllers from having to specify identifiers specific to the view technology being used. A view resolver is responsible for delivering a view technology–specific view object, based on the logical view name. Using view technology–independent logical view names in conjunction with a view resolution strategy provides complete decoupling of controllers returning models and views rendering models. Switching from one view technology to another does not require you to change any controllers or other infrastructural code —merely configuration and files specific to the view technology being used such as JSPs or Velocity templates.

24) The DispatcherServlet models the workflow involved with executing a request. It dispatches requests to controllers and takes care of rendering the response, based on the model and view information the controller returns.

Implementing a web application using Spring Web MVC involves building and setting up controllers,providing views and data to display in the views. All this is linked together using a DispatcherServlet in combination with an ApplicationContext. The DispatcherServlet provides a gateway to the server and acts as the manager of the workflow involved with HTTP-based request-response handling. A special type of context, the WebApplicationContext integrates with the dispatcher servlet and manages all web-related components such as controllers, views, mappings between URLs, and interceptors. The WebApplicationContext doesn't differ much from a "normal" ApplicationContext.

25) A Spring Web MVC application cannot exist without a WebApplicationContext. When using the DispatcherServlet's default configuration, you must provide an XML file defining beans, place it in the /WEB-INF directory of your WAR file, and name it [name of servlet]-servlet.xml unless you specify otherwise.

As already mentioned, it's possible to have multiple DispatcherServlets for one web application. This approach has a similar result as Struts modules. Think carefully about where to place your beans. The xxx–servlet.xml should always contain web-related beans, while the parent application context loaded by the ContextLoaderListener, for example, should contain middle-tier beans, such as datasources, data access objects, and service objects.

26) You've seen a web.xml file defining URL patterns. All URLs matching those patterns will be routed to the Spring DispatchetServlet and picked by one or more HandlerMappings. A HandlerMapping is capable of determining a path of execution through the web application. As we've seen, the execution chain consists of one handler and possibly one or more interceptors.

27) WebContent Interceptor

Spring provides some HandlerInterceptors implementing functionality often needed in web applications. One of those is the WebContentInterceptor, providing functionality for easy modification of caching behavior of a web application and useful generic tasks such as limiting the methods (GET,POST, PUT) that are supported by the webapplication.

28) Spring's most basic controller is the org.springframework.web.servlet.mvc.AbstractController.

Hope you enjoy reading the book.

About the Authors

Rod Johnson is the founder of the Spring Framework and a well-known expert on Java and J2EE.Rod holds a Ph.D. from Sydney University. Originally from a C/C++ background, he has been involved with Java and J2EE since their releases as a developer, architect, and consultant.He is the author of two of the most popular and influential books on J2EE: Expert One-on-One J2EE Design and Development (Wrox, 2002), and J2EE without EJB (Wrox, 2004, with Juergen Hoeller). Both have played a major role in the rise of “agile” J2EE, and the move away from overly complex traditional J2EE architecture.Rod is co-lead of the Spring Framework. He is a popular conference speaker and regularly appears at leading Java events in the US, Europe, and Asia. He serves in the Java Community Process (JCP) on the expert groups of several JSRs.He also has wide consulting experience in banking and finance, insurance, software, and media. He is CEO of Interface21 (www.interface21.com), a consultancy devoted to providing expert J2EE and Spring Framework services.He is actively involved with client projects as well as Spring development.

Juergen Hoeller is co-founder of Interface21, the company providing commercial Spring services from the source. He is a key driver of Spring development and has been release manager since Spring’s inception. His special interests and responsibilities in the project cover a wide variety of topics, from the core container to transaction management, data access, and lightweight remoting.Juergen has a Master’s degree in computer science from the University of Linz, specializing in Java, OO modeling, and software engineering. He is co-author of Expert One-on-One J2EE Development without EJB (Wiley, 2004) and regularly presents at conferences and other events. He is also active in many community forums, including TheServerSide.

Alef Arendsen studied computer sciences at the University of Utrecht. Later, also in Utrecht, Alef started his first company. After this turned out to be too little a challenge, Alef went to work for SmartHaven, an Amsterdam-based VCfunded company providing J2EE components for knowledge management applications. He was responsible for streamlining the development process and designing parts of the component infrastructure. In early 2002, together with Joost van de Wijgerd, Alef founded JTeam, a software company providing J2EE development services. Alef is a core Spring committer and, while remaining involved with JTeam, he is now a consultant for Interface21. He is a frequent speaker at public conferences. Alef can be reached by email at alef@interface21.com. You can also read his blog at http://blog.arendsen.net.

Thomas Risberg is a database developer working for TargetrRx, a pharmaceutical market research company located in Horsham, Pennsylvania. He has many years of experience working with both large and small organizations on various database-related projects ranging from simple data entry programs to large data warehousing implementations. Thomas is a reformed COBOL programmer who came to Java via Xbase, Visual Basic, and PL/SQL. He served as an Oracle DBA for a couple of years but decided that software development was really where his heart was. Thomas has a B.A. degree in information processing from the University of Stockhom, Sweden. He is a certified Oracle Professional DBA and a Sun Certified Java Programmer and J2EE Architect.
Thomas joined the Spring Framework development team in early 2003 and is mostly involved in evolving the JDBC layer. His non-computer–related interests are soccer, photography, and travel.

Colin Sampaleanu has had a long and varied career spanning almost two decades—after a childhood spent tinkering with computers and software—including experience developing for and managing his own retail software company, other years in the C++ shrinkwrap and enterprise software space, experience with Java since the early days of the language, and a complete focus on enterprise Java since the late nineties.
Colin is a currently a principal partner at Interface21, which specializes in Spring training, consulting, and support. Prior to joining Interface21, Colin was Chief Architect at a software incubator / VC.
As a core Spring developer and Interface21 principal, Colin spends much of his time talking and writing about the benefits of Spring, and promoting agile software development architectures and methodologies in general.

8 comments:

Anonymous said...

Well, IMHO that book is completely outdated. Of course you can still work with Spring like that because the newer releases are somehow backwards-compatible but then you are not doing yourself any favor because there have been a lot of productivity enhancements you would not know about. Take a look at the current spring reference documentation. Anyway, nice writeup.

Anonymous said...

Yes. It is outdated. Get "Pro Spring 2.5" or "Spring in Action" 2ed

JP said...

Hi Anonymous,

Thanks for your encouragment.Yes i even studied Spring in Action 2nd edition also.

Thanks
Prashant

Stas Ostapenko said...

Spring in Action 2Ed is a very nice book, I love it :)

JP said...

Stas,

Thanks for your comments.Seen your blog and good one...

All the best

Thanks
Prashant

Anonymous said...

If we glance at the specification of the phrase enjoy, with regards to a close marriage by using a further, although as a experience that is certainly engendered when you've got miltchmonkey a much better partnership with ourselves as well - or perhaps to be a a sense larger unity with your family or perhaps man : then it results in being far more clear that each one any individual needs in your daily course can be adore.

Anonymous said...

Great articlе, just what ӏ wаs
looking for.

mу wеbρаge :: link building

Anonymous said...

Great рοst. I waѕ сheсking cоntinuously this blog and I'm impressed! Very helpful information particularly the last part :) I care for such information much. I was seeking this particular information for a long time. Thank you and best of luck.

Here is my homepage ... Vida Vacations