Spring Core Turorial


Spring framework has its featured spread accross 20 modules. These modules are grouped into

  • Core Container
  • Data Access/Intergration
  • Web
  • AOP (Aspect oriented Programming)
  • Instrumentation
  • Messaging
  • Test

1. Core Container

Core Container consists of below modules

  • Core (spring-core)
  • Beans (spring-beans)
  • Context (spring-context)
  • ContextSupport (spring-context-support)
  • Spring Exression (spring-expression)

spring-core and spring-beans modules provide the fundamental parts of the framework that includes IoC and Dependency Injection. The spring-context is build on top of base provided by Core and Beans modules. It provides a means to access objects like JNDI registry. It inherits features from Beans module and adds support for internationalization, event propagation, resource loading. Application Context is the focal point of the context module. spring-context-support provides support for integrating common third-party libraries into spring applicatin context for caching (EHCache, Guava, JCache), mailing (JavaMail), scheduling (CommonJ, Quartz) and template entines(FreeMarker, Velocity, JasperReports). spring-expression module provides a power Expression language for querying and manipulating an object graph at runtime.

2. Data Access/Intergration

Data Access/Integraion consits of below modules

  • JDBC (spring-jdbc)
  • ORM (spring-orm)
  • JMS (spring-jml)
  • OXM (spring-oxm)

With JDBC abstraction and DAO module (sring-jdbc) we can make the database code clean and simple, and prevent problems resulting from failure to close database resources. It also provide a layer of meaningful exceptions on top of exceptions given by several database servers. It makes user of Spring AOP module to provide transaction management services for objects in a spring application.

Spring ORM module (spring-orm) enables to tie into several ORM frameworks including Hibernate, JDO and iBATIS. Spring transaction management supports both ORM frameworks and JDBC

The spring JMS (spring-jms) contains features for producing and consuming messages. Since Spring 4.1 this provides integraion with spring-messaging

The spring OXM (spring-oxm) provides an abstraction layer that supports Object/XML mapping implementation such as JAXB.

3. Web

This layer consists of

  • Web
  • Web MVC
  • WebSockets
  • Portlet

4. AOP

Supports Aspect Oriented Programming.

5. Instrumentation

Supports Class intrumentation support.

6. Messaging

It provides key abstractions such as Message, MessageChannel and MessageHandler as foundation for messaging applications.

7. Test

Supports the unit testing and integration testing of spring components with JUnit or TestNG.

Spring IoC container

Spring provides two distinct types of containers:

  • BeanFactory
  • ApplicationContext

BeanFactory

BeanFactory is representex by BeanFactory interface. The most important implementations of BeanFactory are:

  • XmlBeanFactory (org.springframework.beans.factory.xml.XmlBeanFactory). This reads the bean definition from an XML file.

Consructor:

	XmlBeanFactory(Resource resource);	

Ex:

1
2
Resource resource = new FileSystemResource("bean.xml");
BeanFactory beanFactory = new XmlBeanFactory(resource);

BeanFactory has 6 methods:

	Object getBean(String name)
	boolean containsBean(String name)
	Object getBean(String name,Class type)
	Class getType(String name)
	boolean isSingleton(String name)
	String[] getAliases(String)

ApplicationContext

ApplicationContext is also spring container. BeanFactory provides basic fuctionality while ApplicationContext provides advanced features for enterprise level applications like i18n, event publishing, JNDI access, Remoting etc.

If By default all singleton beans are created eagerly at the time of ApplicationContext is created. We can change this behaviour to lazy instantiation by using lazy-init attribute of bean tag.

1
	<bean id="mybean" class="..." lazy-init="true"/>

Implementations of ApplicationContext

There are 5 implementations of ApplicationContext

1. ClassPathXmlApplicationContext

This loads the bean definitions/configuration from xml file as class path resource. This requires the CLASSPATH to be set properly.

Ex 1: Single configuration file

ApplicationContext context = new ClassPathXmlApplicationContext("myconfig.xml"); 

Ex 2: Multiple configuration file

ApplicationContext context = new ClassPathXmlApplicationContext(newString[]{"servicesconfig.xml","daoconfig.xml"}); 

2. FileSystemXmlApplicationContext

This loads the bean definitions/configuration from xml file located in file system. This requires the absolute file path to be provided.

Ex:

ApplicationContext context = new FileSystemXmlApplicationContext("c:/myconfig.xml");

3. XmlWebApplicationContext

  • XmlWebApplicationContext is a spring container for web applications.
  • It is an implementation of WebApplicationContext interface which interns extends from ApplicationContext interface.
  • By default every spring web application creates XmlWebApplicationContext to represent ApplicationContext.
  • This loads bean definitions from xml file /WEB-INF/applicationContext.xml.
  • If we want bean definitions to be loaded from multiple configuration files then we can specify the file location in contextConfigLocation parameter of ContextLoaderListener or DispatchServlet in web.xml.

4. AnnotationConfigApplicationContext

AnnotationConfigApplicationContext is when we are using java based configuration for bean definitions instead of xml.

Ex:

1
2
3
4
5
6
public static void main(String[]args){
	/* Creating Spring IoC Container Without XML configuration file*/
	ApplicationContext context= new AnnotationConfigApplicationContext(MyConfig.class);
	MyBean beanObj = context.getBean(MyBean.class);
	beanObj.someMethod();
}

The config class MyConfig can be written as:

1
2
3
4
5
6
7
@Configuration
public class MyConfig{
	@Bean
	public MyBean myBeanId(){
		return new MyBean();
	}
}

Notes:

  • The class AnnotationConfigApplicationContext and the annotations @Configuration , @Bean are introduced in Spring 3.0.

5. AnnotationConfigWebApplicationContext

This is web application counter part for AnnotationConfigApplicationContext

By default spring web application uses XmlWebApplicationContext as ApplicationContext. To change this to AnnotationConfigWebApplicationContext by changing contextClass parameter of ContextLoaderListener or DispatchServlet in web.xml.

Ex: For ContextLoaderListener

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<web-app>
	<context-param>
		<param-name>contextClass</param-name> 
			<param-value>   
				org.springframework.web.context.support.AnnotationConfigWebApplicationContext
		</param-value> 
	</context-param> 
	<context-param>
		<param-name>contextConfigLocation</param-name> 
		<!--MyConfig must be annotated with @Configuration-->
		<param-value> MyConfig</param-value>
	</context-param>
	<listener>
		<listener-class> 
			org.springframework.web.context.ContextLoaderListener 
		</listener-class>
	</listener> 
</web-app> 

Ex: For DispatcherServlet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<web-app>
	<servlet>
		<servlet-name>mydispatcher</servlet-name>
		<servlet-class > org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param> 
			<param-name>contextClass</param-name> 
			<param-value>            
			 org.springframework.web.context.support.AnnotationConfigWebApplicationContext     
			</param-value>
		</init-param> 
		<init-param>   
			<param-name>contextConfigLocation</param-name>    
			<!--MyConfig must be class annotated with @Configuration-->
			<param-value> MyConfig </param-value>
		</init-param>
	</servlet>
	<servlet-mapping> 
		<servlet-name>mydispatcher</servlet-name>    
		<url-pattern>*.htm</url-pattern>
	</servlet-mapping>
</web-app>

Container Overview:

The org.springframework.contex.ApplicationContext represents the sprring IoC container. Spring IoC container is responsibel for intantiating, configuring and assembling a forementioned beans. The container gets its instructions on what objects to instantiate by reading configuration metadata.

Configuration metadata

Spring IoC Container is totally decoupled from the format in which configuration metadata is written. This configuration metadata can be supplied in three forms

  • XML-based configuration
  • Annotation-based configuration
  • Java-based configuration

XML-based configuration

XML-based configuration shows these beans configured as elements inside toplevel element.

Ex:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?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.xsd">

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

</beans>

Annotation-based configuration

For detailss on annotaion based configuratin refere to

Java-based configuration

Instantiating Container

Bean overview Dependencies Bean Scopes Bean definition inheritence Annotation based container configuration Classpath scanning and mananged components Using JSR330 Java based container configuration