Core Spring : Basics

Spring is one of the most popular application development frameworks for writing enterprise Java applications. The first version was written by Rod Johnson, and was first released under the Apache 2.0 license in June 2003. There is a lot of confusion about the definition of the IoC container – some equate it with a design pattern called Dependency Injection – but in reality IoC is much larger than dependency injection. Here IOC means that we have inverted the control of creating the object from using the new opertor to the container or framework.  The Spring IoC container enforces dependency injection in its various forms and employs a number of established design patterns to achieve this. The main idea behind Inversion of Control as a concept is that component dependencies, lifecycle events, and configuration reside outside of the components themselves, and in the case of Spring, in the framework.  Spring’s Inversion of Control framework is based on some best practice patterns – aspects of Spring IoC resemble and include the Factory and Observer patterns, and its most prominent feature is its implementation of a framework which enforces use of the dependency injection pattern.

IoC is a generic term meaning rather than having the application call the methods in a framework, the framework calls implementations provided by the application.

DI is a form of IoC, where implementations are passed into an object through constructors/setters/service look-ups, which the object will ‘depend’ on in order to behave correctly.

For a quick overview of Dependency injection you can refer to my post here.

Lets get started. We will be building a java project and use spring for bean initialisation, dependencies injection etc. I will be using maven for getting spring jars. You can also go to the spring website and download all the jars together. Then include related dependencies like common.logging , aop alliance etc. Through maven, you jst need to tell what jars is diretly used, all the related dependencies are downloaded automatically. I have integrated maven with my eclipse.

For a quick overview of maven you can refer to my post  – Maven : Setup and Basics; Maven : A simple webApp; Maven : Eclipse Integration

Create a new Maven Project. File -> New project (other) select maven project:

CoreSpring1

CoreSpring2

A new maven project is created with no java files as we didnt selected any exsisting artifact. a pom.xml is created at the root level of the project which will be having no dependencies. Now lets add spring dependencies to this project in pom.xml. Your pom.xml should look like this:


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>mynotes.corespring.test</groupId>
<artifactId>MyNotes_core_spring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<org.springframework.version>4.0.3.RELEASE</org.springframework.version>
</properties>
<dependencies>
<!-- Core utilities used by other modules. Define this if you use Spring
Utility APIs (org.springframework.core.*/org.springframework.util.*) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<!-- Bean Factory and JavaBeans utilities (depends on spring-core) Define
this if you use Spring Bean APIs (org.springframework.beans.*) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<!-- Application Context (depends on spring-core, spring-expression, spring-aop,
spring-beans) This is the central artifact for Spring's Dependency Injection
Container and is generally always defined -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
</dependencies>
</project>

As soon as you save this, maven should look into these dependencies from your local repository, else it will download from new. If for some reson its not downloading try right clicking your project -> Maven -> Update project.

Lets create a class Employee:


package mynotes.corespring.test;

public class Employee {

public void getDetails(){
System.out.println("Hello! I am an Employee..");
}

}

Now create a spring configuration file – spring.xml


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<bean id="employee" class="mynotes.corespring.test.Employee">
</bean>

</beans>

Notice that we have define a bean pointing to the Employee class we just created.

Lets ceate a App.java as a starting point of our application:


package mynotes.corespring.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class App {

public static void main(String[] args) {
ApplicationContext context=new FileSystemXmlApplicationContext("spring.xml");
Employee employee=(Employee) context.getBean("employee");
employee.getDetails();
}

}

Tthe overall structure of your project might look like this:

CoreSpring3

Notice here that even though we mentioned only 3 dependencies in pom.xml maven automativally downloaded the related dependencies. Lets run our App.java. Output:


Hello! I am an Employee..

Now for obvious resons you must be thinking thats it would be easy to create a object with new operator and call the method, but the important thing to note here is that here spring has created the object for us from the configuration file and as we go ahead when object became more complex with various relationship the advantage will then be visible.

Noticed that we used FileSystemXmlApplicationContext to load the spring.xml. We can use other classes as well like ClassPathXmlApplicationContext. ClassPathXmlApplicationContext will read files from your classpath. They must be in classes folder of your web application or in a jar in your libfolder. FileSystemXmlApplicationContext can access all your file system, for example c:/config/applicationContext.xml.

Changing to ClassPathXmlApplicationContext , we have to move our spring.xml to the classpath or to some package.

CoreSpring4

Spring is a container of beans or factory of beans. Like tomcat is a servlet container meaning tomcat creats a servelet object which are required to run your web application. Similarly spring is a container of beans and any pojo can be controlled by spring and manages it lifecycle, scope etc.

You can create beans using BeanFactory as well. Both BeanFactory and ApplicationContext provides way to get bean from Spring IOC container by calling getBean(“bean name”), but there are some difference in there working and features provided by them. One difference between bean factory and application context is that former only instantiate bean whenyou call getBean() method while ApplicationContext instantiate Singleton bean when container is started, It doesn’t wait for getBean to be called.

Here are few more difference between BeanFactory and ApplicationContext which is mostly based upon features supported by them.

  • BeanFactory doesn’t provide support for internationalization i.e. i18n but ApplicationContext provides support for it.
  • Another difference between BeanFactory vs ApplicationContext is ability to publish event to beans that are registered as listener.
  • One of the popular implementation of BeanFactory interface is XMLBeanFactory while one of the popular implementation of ApplicationContext interface is ClassPathXmlApplicationContext. On Java web application we use WebApplicationContext which extends ApplicationContext interface and adds getServletContext method.
  • If you are using auto wiring and using BeanFactory than you need to register AutoWiredBeanPostProcessor using API which you can configure in XML if you are using ApplicationContext.

BeanFactory is used when the resource is scarce (for example, mobile applications) and ApplicationContext is used when there is no scarcity of resources.

Spring has 7 core modules:

  • The core container module
  • Application context module
  • AOP module
  • JDBC abstraction and DAO modules
  • ORM intergration modules
  • Web module
  • MVC framework modules

One of the chief advantages of spring framework is its layered architechture, which allows you to be selective about which of its component you want while also providind a cohesive framework for j2ee app development.

 

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 )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: