Spring_Framework_Overview_Part1

Page 1

Spring Framework Overview (Part 1) A quick overview to understand Spring Framework

Written by: Alan Choy Principal Consultant, eIT Consulting Inc.

http://www.eitconsulting.ca Email: info@eitconsulting.ca

1


INTRODUCTION Java as a language provides a wealth of functionalities and components for application development. The Enterprise Edition of Java (i.e. Java EE) took a step further to define many specifications or “standard”, in an attempt to provide the platform for developing enterprise applications. However, more evolvements have happened in the last few years in the industry, and it became more and more apparent that a lightweight architecture of framework is very desirable to enhance reusability, testability and productivity, especially in light of other waves of development process and methodology changes, such as Agile. Among all the lightweight containers, Spring framework stands out as the most popular and the most widely accepted framework for enterprise application development, with good reasons. There are significant quantity of books and materials about Spring framework available today, but I found most of them are either too simple, which hardly demonstrates the power of Spring, or too complicated, which is too tedious to grasp the main idea for someone who is new to the topic. In this series of Spring framework overview articles, I attempt to provide the optimal details of important concepts, plus adequate complexity of code examples to show what Spring framework is really about. In this first installment of the series of articles, I’ll focus on the core technologies and concepts of Spring framework, namely IoC (Inversion of Control), DI (Dependency Injection) and Autowiring. I’ll also explain and provide examples regarding these concepts using POJO (Plain Old Java Object). This is especially important as POJO usually depends a lot less to the container than traditional J2EE development. It also means it is much easier to setup the appropriate environment (i.e. less runtime infrastructure setup) to perform unit test in an efficient manner. In the subsequent installments of this series, I’m going to discuss other very useful components of Spring framework, which includes the Spring AOP (Aspect-Oriented Programming), Spring MVC (Mode-View-Controller) and Spring transaction management support. Please stay tuned.

ABOUT THE AUTHOR Alan Choy is the Principal Consultant of eIT Consulting Inc., which specialized in providing professional services and solution to enterprise application development and maintenance. Alan has held this position since October 2005. Alan has over 11 years of experience in enterprise application development, in multiple international companies, including Ericsson Research Canada, Motorola (Canada) Inc., CGI Group Inc. and Telus Corporation. In the past few years Alan has focused on Java and J2EE platform, with vast experience in many open source technologies such as Spring framework, AOP and Hibernate.

2


INVERSION OF CONTROL It is fair to say that Inversion of Control (IoC) is the single most important concept of Spring framework. IoC underpins a lot of functionalities provided by Spring, so it is critical to understand this at the first place. So what is IoC? In traditional application development, the control of logic, relationships and flow are usually implemented and maintained within the application codes. In the IoC world, the control is handed over to Spring framework, which calls the application codes (usually POJO) instead of the codes calling the framework, and hence the name “Inversion” of Control. This is also known as Hollywood Principle – “Don’t call us, we’ll call you”! The following was an excerpt from an article written by Ralph Johnson and Brian Foote, which describes what IoC is about: One important characteristic of a framework is that the methods defined by the user to tailor the framework will often be called from within the framework itself, rather than from the user's application code. The framework often plays the role of the main program in coordinating and sequencing application activity. This inversion of control gives frameworks the power to serve as extensible skeletons. The methods supplied by the user tailor the generic algorithms defined in the framework for a particular application. In Spring, the objects that are instantiated and managed by the Spring IoC Container are referred to as beans. These beans, together with their relationships and dependencies, are defined in the configuration metadata (i.e. xml format) used by the container. Below is an example of the XML-based configuration metadata:

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <!—- bean to be created by Spring IoC Container --> <bean id="mlb" class="ca.eitconsulting.spring.partone.MajorLeagueBaseball"/> </beans>

In this simple example, a bean is defined with an id (i.e. mlb), for the class MajorLeagueBaseball (yes, you can tell I am a baseball fan!), using the fully-qualified name of the class. This XML file should be placed in the classpath of the application.

3


Below is the Java code to use this metadata configuration file within Spring framework: private final String configFile = "beans.xml"; Resource resource = new FileSystemResource(configFile); BeanFactory factory = new XmlBeanFactory(resource); MajorLeagueBaseball mlb = (MajorLeagueBaseball)factory.getBean("mlb"); System.out.println("Simple test of Spring IoC Container");

In the code, it first instantiates a Resource object to load the XML metadata configuration file. BeanFactory is the root interface for accessing Spring IoC Container, and the centralized registry of application components (alternately you can use ApplicationContext interface, which enhances BeanFactory functionality in a more framework oriented style). This is the basic client view of the container. Below is the MajorLeagueBaseball class, which is super simple, and contains only the default constructor: public class MajorLeagueBaseball { public MajorLeagueBaseball() { System.out.println("MLB Season 2006!"); } }

After running the code, the output will be the following: MLB Season 2006! Simple test of Spring IoC Container

There are other attributes which can be used to define the bean behavior. Some of them I will go into more details in the subsequent sections as they are critical and useful concepts to grasp. For the other relatively simpler attributes please consult Spring framework references for more details. Instead of using constructor to create bean, alternatively we can use bean factory approach, which the factory method of an existing bean within the container is invoked to create instance bean. Please see the example below for the corresponding metadata configuration: <!—- factory bean, which contains createInstance() method --> <bean id="mlbFactory" class="ca.eitconsulting.spring.partone.MajorLeagueBaseballFactory"/> <!—- bean to be created via the factory bean --> <bean id="mlb" factory-bean="mlbFactory" factory-method="createInstance"/>

4


DEPENDENCY INJECTION Dependency Injection (DI) is tightly coupled with IoC, hence without a doubt that this is the right place to introduce this concept. In a typical application, there are multiple classes which work together to perform certain task(s), and hence inter-relate with each other in some sort of relationships. Instead of defining the relationships within the application codes, these kinds of dependency can be defined in the XML metadata configuration, and the container will be responsible to “inject� the relationships when the bean is created. In Spring framework, DI exists in two major variants, which are setter injection and constructor injection. Setter injection is used when setter methods are invoked after the bean has been instantiated. Below is the XML configuration for setter injection: <bean id="mlb" class="ca.eitconsulting.spring.partone.MajorLeagueBaseball"> <property name="commissioner" value="Bud Selig"/> </bean>

The property tag is used to tell Spring IoC container to look for the setter method for the attribute commissioner (i.e. setCommissioner()), and pass in the value attribute as the input parameter to the method. Below is the modified Java code of MajorLeagueBaseball class: public class MajorLeagueBaseball { private String commissioner; public MajorLeagueBaseball() { System.out.println("MLB Season 2006!"); } public void setCommissioner(String commissioner) { this.commissioner = commissioner; System.out.println("MLB Commissioner is " + this.commissioner); } public String getCommissioner() { return this.commissioner; } }

After running the code, the output will be the following: MLB Season 2006! MLB Commissioner is Bud Selig Simple test of Spring IoC Container

5


Constructor injection is used when a constructor (with a number of arguments) is invoked while the bean is being instantiated. Additionally, calling a static factory method with specific arguments to construct the bean can be considered as equivalent too. Below is the XML metadata configuration for constructor injection: <bean id="mlb" class="ca.eitconsulting.spring.partone.MajorLeagueBaseball"> <constructor-arg type="java.lang.String" value="Bud Selig"/> <constructor-arg type="int" value="30"/> </bean>

The constructor-arg tag is used to tell Spring IoC container to look for a constructor of MajorLeagueBaseball class, which takes two arguments with the corresponding type (the parameter order in the constructor signature does not need to match the order in the XML configuration file). In case there is ambiguity in the constructor arguments (i.e. with two or more parameters of the same data type), then the alternative is to specify index attribute to tell IoC container the expected order. Please note that index attribute is 0 based. Below is the example of using index attribute: <bean id="mlb" class="ca.eitconsulting.spring.partone.MajorLeagueBaseball"> <constructor-arg index="0" value="Bug Selig"/> <constructor-arg index="1" value="30"/> </bean>

Below is the modified Java code of MajorLeagueBaseball class: public class MajorLeagueBaseball { private String commissioner; private int numTeam; public MajorLeagueBaseball(String commissioner, int numTeam) { this.commissioner = commissioner; this.numTeam = numTeam; System.out.println("MLB Season 2006 using Constructor with arguments!"); } }

After running the code, the output will be the following: MLB Season 2006 using Constructor with arguments! Simple test of Spring IoC Container

6


AUTOWIRING Spring IoC container is able to autowire relationships between collaborating beans. It means the container will automatically resolve the bean relationships by inspecting the BeanFactory contents. Autowiring in Spring happens at bean level, which means it is possible to autowire some beans in the container but not the others, and it would save a significant amount of configuration typing and maintenance effort. Below is an example of XML metadata configuration: <bean id="worldSeriesChamp" class="ca.eitconsulting.spring.partone.BaseballTeam"> <constructor-arg type="java.lang.String" value="St. Louis Cardinals"/> </bean> <bean id="mlb" class="ca.eitconsulting.spring.partone.MajorLeagueBaseball" autowire="byName"> <constructor-arg type="int" value="30"/> <constructor-arg type="java.lang.String" value="Bug Selig"/> </bean>

From the above XML configuration, the bean worldSeriesChamp is instantiated as a BaseballTeam object. Autowiring by name is specified in the mlb bean, with an attribute called worldSeriesChamp. In such case, Spring IoC container will autowire the object to the attribute because their names match. Below is the Java code of BaseballTeam class: public class BaseballTeam { private String name; public BaseballTeam(String name) { this.name = name; System.out.println("MLB Baseball team is " + this.name); } }

Below is the modified Java code of MajorLeagueBaseball class: private BaseballTeam worldSeriesChamp; public void setWorldSeriesChamp(BaseballTeam worldSeriesChamp) { this.worldSeriesChamp = worldSeriesChamp; System.out.println("Set worldSeriesChamp property by autowiring"); } public BaseballTeam getWorldSeriesChamp() { return this.worldSeriesChamp; }

7


After running the code, the output will be the following: MLB Season 2006 using Constructor with arguments! MLB Baseball team is St. Louis Cardinals Set worldSeriesChamp property by autowiring Simple test of Spring IoC Container

On one side autowiring is very powerful. However, it is even more important to understand the advantages and disadvantages of using this technique. Below are some common pros and cons: Some advantages of autowiring include: Autowiring can significantly reduce the effort of configuration required Autowiring can keep the configuration valid automatically as the project evolves Autowiring can force the naming convention of bean and java code to be unified Some disadvantages of autowiring include: The dependencies and relationships between beans are not explicitly stated Autowiring by type would only work if there is only one instance of a specific type instantiated within the container

SUMMARY In this article you have learnt about the core technologies and concepts used in Spring framework, namely Inversion of Control (IoC), Dependency Injection (DI) and Autowiring. Other different modules of Spring framework are built upon these foundations, hence it is very critical to make sure you understand them from inside out. Furthermore, as you could tell, a lot of these functionalities are centralized in using metadata configuration and take advantage of the power of the Spring container, rather than using the application codes. It also means that the codes will be largely focus on implementing the business logics, and hence increase the productivity. As mentioned in the introduction, this article served as the first installment of a series of articles, which covers the major aspects of Spring framework. The next installment will focus on Aspect Oriented Programming (AOP), and how it is integrated into Spring (i.e. the two major technologies cross road with each other). Stay tuned and you won’t be disappointed.

8


RESOURCES Below are some very useful resources for Spring framework: Download the Spring framework binaries, source code and API from officially Spring framework website Professional Java Development with the Spring Framework By Rod Johnson Published by Wiley; ISBN: 0764574833 Beginning Spring Framework 2 By Thomas Van de Velde, Christian Dupuis and Naveen Balani Published by Wiley; ISBN: 047010161X

FEEDBACK Please let us know whether this tutorial was helpful to you, and how we could make it better. Your comments will be valuable to us, and will be taken into consideration for the subsequent installments of this series of articles. Furthermore, we would also like to hear about other tutorial topics you would like to see covered in the future. For questions about the content of this tutorial, please contact the author, Alan Choy, at alan.choy@eitconsulting.ca.

9


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.