Home » Java and J2EE » Spring Fundamental Tutorial

Spring Fundamental Tutorial

Spring First Tutorial

Since intention of this tutorial is to give a brief foundation of Spring framework so its start with covering the following basic modules first and later it would move to advance topics. Tutorial is based on spring 3.0 version.

§Introduction to Spring

§Features added in Spring 3.0+ version

§Spring Framework

§Spring Modules

§Spring IOC & Dependency Injection

§Application Context & Bean Factory

§Spring Bean Configuration

§Auto-wiring in Spring configuration


§Working with Spring Name spaces

§Using Inner Beans 


§Introduction to Spring

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. Spring framework is a layered architecture consisting of seven well-defined modules. The Spring modules are built on top of the core container, which defines how beans are created, configured, and managed, as shown in next Figure .


§Features added in Spring 3.0+ version

  • Spring 3.0 framework supports Java 5. It provides annotation based configuration support. Java 5 features such as generics, annotations, varargs etc can be used in Spring.
  • A new expression language Spring Expression Language SpEL is being introduced. The Spring Expression Language can be used while defining the XML and Annotation based bean definition.
  • Spring 3.0 framework supports REST web services.
  • Data formatting can never be so easy. Spring 3.0 supports annotation based formatting. We can now use the @DateFimeFormat(iso=ISO.DATE) and @NumberFormat(style=Style.CURRENCY) annotations to convert the date and currency formats.
  • Spring 3.0 has started support to JPA 2.0.
  • Apart from these main features there are lots of exiting improvements over the last revisions are also there.


§Spring Framework

§Spring Modules

The core container: The core container provides the essential functionality of the Spring framework. Primary component of the core container are BeanFactory and Application Context, Bean Factory 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. Application Context is build on top of Bean factory and provides more functionalities, like integration with AOP/messaging resources/events etc.

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. Spring provides option to specify configuration by XML or Java file based approach.

Spring AOP: AOP is very emerging feature now days which provides more modularity in programming by separating the cross cutting the concerns from main business logic.  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 provides 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.

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. . Spring DAO’s JDBC-oriented exceptions comply to its generic DAO exception hierarchy.

Spring ORM: Spring provides good abstraction layer to integrate with most of the popular ORM tools in market. The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring’s generic transaction and DAO exception hierarchies.

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. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects.

Spring MVC framework: Spring provides a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and support most of the view technologies like JSP, Velocity, Tiles, iText, and POI.Spring framework functionality can be used in any J2EE server and most of it also is adaptable to non-managed environments. Concentrating more on allowing reusable business and data-access objects that are not tied to specific J2EE services. Such objects can be reused across J2EE environments (Web or EJB), standalone applications, test environments, and so on, without any hassle.


§Spring IOC & Dependency Injection

The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.In a typical IOC scenario, the container creates all the objects, wires them together by setting the necessary properties, and determines when methods will be invoked. The three implementation pattern types for IOC are listed below.

  1. Dependencies are assigned through JavaBeans properties (for example, setter methods).
  2. Dependencies are provided as constructor parameters and are not exposed as JavaBeans properties.

Lets see how Spring Uses the Power of simple bean

Most of the traditional frame works forces you to implement their life cycle methods

public class HelloWorldBean implements SessionBean {
    public void ejbActivate() {
    public void ejbPassivate() {

    public void ejbRemove() {
    public void setSessionContext(SessionContext ctx) {

    public String sayHello() {
    return "Hello World";}

    public void ejbCreate() {

The SessionBean interface would let you hook into the EJB’s lifecycle by implementing several lifecycle callback methods, even if you didn’t need to. Spring avoids (as much as possible) littering your application code with its API. Spring almost never forces you to implement a Spring-specific interface or extend a Spring-specific class. Instead, the classes in a Spring-based application often have no indication that they’re being used by Spring. At worst, a class may be annotated with one of Spring’s annotations, but is otherwise a POJO.

  public class HelloWorldBean {
     public String sayHello() {

Isn’t that better? Gone are all of those noisy lifecycle methods. HelloWorldBean doesn’t implement, extend, or even import anything from the Spring API Dependency injection involves giving an object its dependencies as opposed to an object having to acquire those dependencies on its own.

Comparing with the traditional approach of programming vs the spring mechanism. With an interesting example taken from the Book : “Spring in Action 3.0”

Problem: RescueDamselQuest : Mission to rescue a pricess. If we analyse the class written bellow for a moment we can figure out several limitations as described further.

public class DamselRescuingKnight implements Knight {
   private RescueDamselQuest quest;
   public DamselRescuingKnight() {
   //Tightly coupled to RescueDamselQuest
     quest = new RescueDamselQuest();

   public void embarkOnQuest() throws QuestException {

Observed Drawbacks:

  • DamseRescueKnight is tightly coupled to RescueDamselQuest
  • Restricting the ability of Knights for embark on a Quest
  • Terrible writing for test case for DamseRescueKnight , you’d like to be able to assert that the quest’s embark() method is called when the knight’s embarkOnQuest() is called,but is difficult to write such test case.

Better approach to reduce the coupling between the DamselRescuingKnight and RescueDamselQuest, isn’t it.

public class BraveKnight implements Knight {
   private Quest quest;
   public BraveKnight(Quest quest) {
     this.quest = quest;

   public void embarkOnQuest() throws QuestException {

Observed advantages:

  • BraveKnight does not create own Quest
  • Rather he is given a quest at the construction time
  • What more he is give a typed Quest that can receive any kind of Quest, The point here is that BraveKnight isn’t coupled to any specific implementation of Quest

That’s the key benefit of DI—loose coupling. Writing the use case for the above problems also gets more meaning full approach.

   public void knightShouldEmbarkOnQuest() throws QuestException {
      Quest mockQuest = mock(Quest.class);
      BraveKnight knight = new BraveKnight(mockQuest);
      verify(mockQuest, times(1)).embark();

Here you’re using a mock object framework known as Mockito to create a mock implementation of the Quest interface. You really not need to wait to hit the real Quest while Unit test


§Application Context & Bean Factory

Two of the most fundamental and important packages in Spring are the org.springframework.beans and org.springframework.context packages. The BeanFactory provides an advanced configuration mechanism capable of managing beans (objects) of any nature, using potentially any kind of storage facility

The ApplicationContext builds on top of the BeanFactory (it’s a subclass) and adds other functionality such as easier integration with Springs AOP features, message resource handling , event handling, declarative mechanisms to create the ApplicationContext and optional parent contexts, and application-layer specific contexts such as the WebApplicationContext, among other enhancements. Best option is to use the ApplicationContext, since it offers all the features of the BeanFactory and adds on to it in terms of features

Code snippet of getting handler to ApplicationContext/BeanFactory. By providing the reference of the bean configuration file we can get hander of Bean Factory of Application context.

ClassPathResource res = new ClassPathResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");


ApplicationContext context = new FileSystemXmlApplicationContext ("C:/Users/manjul/../src/Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");


ApplicationContext context = new FileSystemXmlApplicationContext ("C:/Users/manjul/../src/Beans.xml");
BeanFactory factory = (BeanFactory) context
HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");

I would suggest to use Application Context over the BeanFactory as it provides you all what BeanFactory does plus some other features. The most commonly used ApplicationContext implementations are:

  • FileSystemXmlApplicationContext: This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor.
  • ClassPathXmlApplicationContext This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.
  • WebXmlApplicationContext: This container loads the XML file with definitions of all beans from within a web application.


§Spring Bean Configuration

A bean definition can contain a lot of configuration information, including constructor arguments, property values, and container-specific information such as initialization method, static factory method name, and so on.A child bean definition inherits configuration data from a parent definition. The child definition can override some values, or add others, as needed.Spring Bean definition inheritance has nothing to do with Java class inheritance but inheritance concept is same. You can define a parent bean definition as a template and other child beans can inherit required configuration from the parent bean.When you use XML-based configuration metadata, you indicate a child bean definition by using the parent attribute, specifying the parent bean as the value of this attribute.

The bean definition contains the information called configuration metadata which is needed for the container to know the followings:

  • How to create a bean
  • Bean’s lifecycle details
  • Bean’s dependencies

All the above configuration metadata translates into a set of the following properties that make up each bean definition. Following attributes used with bean tags and their usage is given in below table.

Configuring Spring. Spring provides several ways of defining the Bean configurations as listed below. But I preferably choose XML based configuration, as it provides centralized view of the artifacts to analyze the whole configuration very easily. But its totally up to you that which mechanism you like to implement in your application.

Spring Configuration MetaData

  1. XML based configuration file.
  2. Annotation-based configuration
  3. Java-based configuration

In a large project structure, the Spring’s bean configuration files are located at different folders for easy maintainability and modular. For example:

  1. Spring-Common.xml in common folder,
  2. Spring-Connection.xml in connection folder,
  3. Spring-ModuleA.xml in ModuleA folder…and etc.

Sample view of Bean configuration File

<beans xmlns="http://www.springframework.org/schema/beans”
<!-- A simple bean definition -->
<bean id="..."singleton">
<!-- collaborators and configuration for this bean go here -->
<!-- A bean definition with lazy init set on -->
<bean id="..." lazy-init="true">
<!-- collaborators and configuration for this bean go here -->
<!-- A bean definition with initialization method -->
<bean id="..." init-method="...">
<!-- collaborators and configuration for this bean go here -->
<!-- A bean definition with destruction method -->
<bean id="..." destroy-method="...">
<!-- collaborators and configuration for this bean go here -->
<!-- more bean definitions go here -->


Scopes of the Beans


§Auto-wiring in Spring configuration

You have seen how to declare beans using the <bean> element and inject <bean> with using <constructor-arg> and <property> elements in XML configuration file. The Spring container can autowire relationships

between collaborating beans without using <constructor-arg> and <property> elements which helps cut down on the amount of XML configuration you write for a big Spring based application. Using following ways/mode.

  • No
  • byName
  • byType
  • Constructor
  • Autodetect

Now we know how to set manual wiring !

<bean id=”customer”>
<property name=”person” ref=”person” />

<bean id=”person” />

Autowiring by property name.

Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.

Spring will auto wired it via setter method – “setPerson(Person person)“.

<bean id=”customer” autowire=”byName” />
<bean id=”person” />

Autowiring by property datatype.

Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown.

Spring will auto wired it via setter method – “setPerson(Person person)“.

<bean id=”customer” autowire=”byType” />
<bean id=”person” />

Auto-wire Constructore.

Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.

Spring auto wired it via constructor method – “public Customer(Person person)“.

<bean id=”customer” autowire=”constructor” />
<bean id=”person”.manjul.spring.samples.Person” />

Auto-wire Autodetect

Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

<bean id=”customer” autowire=”autodetect” />
<bean id=”person” />

Limitations of Autowiring 

Limitations with autowiring:Autowiring works best when it is used consistently across a project. If autowiring is not used in general, it might be confusing to developers to use it to wire

only one or two bean definitions. Though, autowiring can significantly reduce the need to specify properties or constructor arguments but you should consider the limitations and

disadvantages of autowiring before using them.Limitations Description

Overriding possibility, We can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.

Primitive data types,  We cannot autowire so-called simple properties such as primitives, Strings, and Classes.

Confusing nature Autowiring is less exact than explicit wiring, so if possible prefer using explict wiring.



Using annotations for the defining Spring configuration file and beans configurations
@Configuration & @Bean Annotations

public class HelloWorldConfig {

public HelloWorld helloWorld(){
return new HelloWorld();

This Is equivalent to
<bean id=”helloWorld” />

While retrieving the bean reference:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class, OtherConfig.class);
ctx.register(AdditionalConfig.class); ctx.refresh();
MyService myService = ctx.getBean(MyService.class);

Autowired Annotation
We have seen how can we define autowiring in configuration file.

We can also specify auto wiring using @Autowired Annotation
Through setter method
public void setPerson(Person person) {
this.person = person;

Through construtor
public Customer(Person person) {
this.person = person;

Through field
private Person person;

By default, the @Autowired will perform the dependency checking to make sure the property has been wired
properly. When Spring can’t find a matching bean to wire, it will throw an exception. To fix it, you can disable
this checking feature by setting the “required” attribute of @Autowired to false. @Autowired(required=false)

The @Qualifier annotation us used to control which bean should be autowire on a field. For example, bean configuration file with two similar person beans.

public class Customer
private Person person;
private int type;
private String action;
//getter and setter methods


§Spring NameSpaces

Namespace configuration has been available since version 2.0 of the Spring framework.

It allows you to supplement the traditional Spring beans application context syntax with elements from additional XML schema. You can find more information in the Spring Reference Documentation. A namespace element can be used simply to allow a more concise way of configuring an individual bean or, more powerfully, to define an alternative configuration syntax which more closely matches the problem domain and hides the underlying complexity from the user. A simple element may conceal the fact that multiple beans and processing steps are being added to the application context. For example, adding the following element from the security namespace to an application context will start up an embedded LDAP server for testing use within the application.

Name spaces are the preset of liberaries created for a significant purpose i.g. utilities, security, aop etc. Some of the popular libraries are listed below:

Spring core

aop – AopNamespaceHandler
c – SimpleConstructorNamespaceHandler
cache – CacheNamespaceHandler
context – ContextNamespaceHandler
jdbc – JdbcNamespaceHandler
jee – JeeNamespaceHandler
jms – JmsNamespaceHandler
lang – LangNamespaceHandler
mvc – MvcNamespaceHandler
oxm – OxmNamespaceHandler
p – SimplePropertyNamespaceHandler
task – TaskNamespaceHandler
tx – TxNamespaceHandler
util – UtilNamespaceHandler
Spring Security
security – SecurityNamespaceHandler
oauth – OAuthSecurityNamespaceHandler
P-Name space

The p-namespace enables you to use the bean element’s attributes, instead of nested <property/> elements, to describe your property values and/or collaborating beans.

Namespace specification need to be added in configuration file as shown below
Traditional way

<bean name=”john-classic”>
<property name=”name” value=”John Doe”/>
<property name=”spouse” ref=”jane”/>

Using name spaces
<bean name=”john-modern”
p:name=”John Doe”
<bean name=”jane”>
<property name=”name” value=”Jane Doe”/>

Util-Name space

Make sure that we need to have correct XSD loaded
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd”

Ex1 : Generic way for configuring property is
<bean id=”…”>
<property name=”isolation”>
<bean id=”java.sql.Connection.TRANSACTION_SERIALIZABLE”

Using namespaces
<bean id=”…”>
<property name=”isolation”>
<util:constant static-field=”java.sql.Connection.TRANSACTION_SERIALIZABLE”/>

Normal Spring FactoryBean implementation, the PropertiesFactoryBean, to instantiate a java.util.Propertie

Ex2 : Without using name spaces

<bean id=”jdbcConfiguration”>
<property name=”location” value=”classpath:com/foo/jdbc-production.properties”/>

Using name spaces

<util:properties id=”jdbcConfiguration” location=”classpath:com/foo/jdbc-production.properties”/>

One of the collection utility for populating values in list.
<bean id=”emails”>
<property name=”sourceList”>

Ex3: Using Namespace:

<util:list id=”emails”>

*Similarly utilities are also available to work with other collections like Map/Set/Properties

§Using Inner Beans

A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-called inner bean.
An inner bean definition does not require a defined id or name; the container ignores these values. It also ignores the scope flag. Inner beans are always anonymous and they are always scoped as prototypes. It is not possible to inject inner beans into collaborating beans other than into the enclosing bean.

<bean id=”outer”>
<!– instead of using a reference to a target bean, simply define the target bean inline –>
<property name=”target”>
<bean> <!– this is the inner bean –>
<property name=”name” value=”Fiona Apple”/>
<property name=”age” value=”25″/>



  1. venkatesh says:

    Thanks, it helped to understand the basics. I could be more better if you use some example code with it.

  2. jenny joshef says:

    Thanks for the article, it gives food idia of spring basics..keep it up. -jenny

  3. I just stopped by to look at this website. It seems to be really interesting and I liked reading it, thanks for the
    good writing!

  4. jeff says:

    got a good notes of spring basics here, would like to read some thing similar simple tut on aspect and spring web modules.

  5. I just came by to learn about this blog. It is really full of great content and I had
    a good time browsing it, thanks for the good article!

  6. Sanjay says:

    Thanks you for this explanatory blog on Spring . I also searching something like this on MVC and Spring Securities. It would be nice if you can explain that topic also.

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: