Spring Application using BeanFactory & ApplicationContext

In this article, we will create simple Spring Application example and test them using BeanFactory & ApplicationContext. This sample demonstrates how spring framework leverages to achieve loose coupling using Dependency Injection (or in general Inversion of Control)

Technology Used

  • Java 1.7
  • Eclipse Kepler IDE
  • Maven 3.0.4
  • Spring-4.0.0-RELEASE

Spring

Spring is the one of the leading open source framework in the Java platform. It brings all the features required to build an enterprise application. Simply, it’s a one stop solution for developing enterprise application allowing developer community to focus on the business and framework handling the infrastructure details.

Advantages of using Spring Framework

  • Lightweight container in terms of size and transparency
  • Allows to develop enterprise application using POJOs which doesn’t requires container like application server
  • Spring framework comes in modular fashion which allows the developer to plug-in the required modules in their application
  • Spring doesn’t re-invent the wheel as the other popular technologies can be integrated easily. Several ORM framework like Hibernate, iBatis, etc and logging framework can be integrated
  • Spring comes with well designed MVC framework for web application, which is advantageous over other MVC framework for its ease of use
  • Spring handles transaction management in a declarative fashion allowing developer to configure how their application’s transaction needs to be handled
  • With Dependency Injection (or Inversion of Control in general concept), dependencies are configured pre-hand in the spring application context xml letting spring to create dependent objects/values on bean instantiation
  • Unit testing of application much easier
  • Spring converts the technology specific exception thrown into consistent unchecked exceptions

Maven-zing Spring Application

This is the simple Application project to demonstrates how exactly Spring works. And we don’t really require Maven here for creating build (war/ear) but having said that this helps to download the required jars from the repository. Using maven command, we can include these downloaded jars into eclipse classpath using mvn eclipse:eclipse

Add Spring-4.0.0 dependencies to the pom.xml

<dependencies>
	<!-- Spring framework -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-core</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context</artifactId>
		<version>${spring.version}</version>
	</dependency>
</dependencies>

Folks who aren’t familiar with Maven concepts or don’t require maven for their project, can download the below jars individually from the spring site and include them in the classpath

  • spring-core-4.0.0-RELEASE
  • spring-context-4.0.0-RELEASE
  • spring-beans-4.0.0-RELEASE
  • spring-aop-4.0.0-RELEASE
  • spring-expression-4.0.0-RELEASE
  • commons-logging-1.1.1
  • aopalliance-1.0

Complete pom.xml here

<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>in.bench.resources</groupId>
	<artifactId>SpringAppCore</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringAppCore</name>
	<url>http://maven.apache.org</url>

	<properties>
		<spring.version>4.0.0.RELEASE</spring.version>
		<java.version>1.7</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
	</dependencies>
</project>

Let’s see coding in action

Create simple Java POJO for employee (simple spring bean) with one public method called printEmployeeDetail()

Employee.java

package com.spring.series.core;

public class Employee {

 private String name;
 private int age;
 private String employeeCode;
 private String designation;

 /**
 * getter's and setter's
 */
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public int getAge() {
 return age;
 }
 public void setAge(int age) {
 this.age = age;
 }
 public String getEmployeeCode() {
 return employeeCode;
 }
 public void setEmployeeCode(String employeeCode) {
 this.employeeCode = employeeCode;
 }
 public String getDesignation() {
 return designation;
 }
 public void setDesignation(String designation) {
 this.designation = designation;
 }

 /**
 * This method prints the employee details
 */
 public void printEmployeeDetail(){

 System.out.println("Employee Name \t\t: " + name);
 System.out.println("Employee Age \t\t: " + age);
 System.out.println("Employee Code \t\t: " + employeeCode);
 System.out.println("Employee Designation \t: " + designation);
 }
}

Create Spring Bean Configuration file (Spring XML)

SpringContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

 <bean id="employee" class="com.spring.series.core.Employee">
 <property name="name" value="Mark"></property>
 <property name="age" value="32"></property>
 <property name="employeeCode" value="E10910"></property>
 <property name="designation" value="Software Architect"></property>
 </bean>
</beans>

Note: Name of the Spring Bean Configuration file can be anything (not necessary to have SpringContext.xml) and it’s your choice. But, in the enterprise application keep these file names appropriate to the business context. So that it will increase the readability of the application.

Project Structure in Eclipse (Package Explorer view)

SpringAppCore1

Test the Application that’s exactly …. Run it!

Having done with coding of Spring Bean (i.e.; Employee POJO) and configured necessary Spring bean XML, it’s time to execute and see the magic of Spring Framework

Test Case 1: Using BeanFactory

This test unit loads the spring context xml from the classpath and invokes the printEmployeeDetail() method of Employee POJO & prints all details of the configured employee object.

Note: As of Spring 3.1, XmlBeanFactory has been deprecated

TestEmployee.java

package com.spring.series.core;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class TestEmployee {

 public static void main(String[] args) {
 testBeanFactory();
 }

 private static void testBeanFactory(){
 /**
 * deprecated as of spring 3.1
 * http://docs.spring.io/spring/docs/4.0.0.RELEASE/javadoc-api/org/springframework/beans/factory/xml/XmlBeanFactory.html
 */
 Resource resource = new ClassPathResource("com/spring/series/core/springcontext.xml");
 BeanFactory beanFactory = new XmlBeanFactory(resource);
 Employee employee = (Employee) beanFactory.getBean("employee");

 System.out.println("Spring Application Demo using BeanFactory\n");

 // invoke print() method of Employee class
 employee.printEmployeeDetail();
 }
}

Output in console

Spring Application Demo using BeanFactory

Employee Name              : Mark
Employee Age                : 32
Employee Code              : E10910
Employee Designation       : Software Architect

Test Case 2: Using ApplicationContext

This too loads the spring context xml from the classpath and invokes the printEmployeeDetail() method of Employee POJO & prints all details of the configured employee object but this time using ApplicationContext, a superset of BeanFactory. We will see, difference at the end of this example.

TestEmployee.java

package com.spring.series.core;

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

public class TestEmployee {

 public static void main(String[] args) {
 testApplicationContext();
 }

 private static void testApplicationContext(){

 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/spring/series/core/SpringContext.xml");
 Employee employee = (Employee) applicationContext.getBean("employee");

 System.out.println("Spring Application Demo using ApplicationContext\n");

 // invoke print() method of Employee class
 employee.printEmployeeDetail();
 }
}

Output in console

Spring Application Demo using ApplicationContext

Employee Name              : Mark
Employee Age               : 32
Employee Code              : E10910
Employee Designation       : Software Architect

So folks developed & tested a simple Spring Application using BeanFactory and ApplicationContext. As I said earlier, it’s time to see what the difference between them.

 BeanFactory v/s ApplicationContext in Spring

BeanFactory
(org.springframework.beans)
ApplicationContext
(org.springframework.context)
Instantiates bean lazily i.e.; when ctx.getBean(“beanName”) is invoked from application
Eg; BeanFactory bf = new XmlBeanFactory(“SpringXml”);
Instantiates bean eagerly i.e.; upon ApplicationContext startup/loaded.
eg; ApplicationContext app = new ClassPathXmlApplicationContext(“SpringXml”);
No Supports for I18N. Supports for Internalization (I18N)
No Supports for Annotation Supports Annotation based Dependency Injection (DI)
Recommended to use in small lightweight application like Mobile, Applet, etc AppplicationContext best suited for enterprise application
Very limited access i.e.; low level resources It is very convenient to load resources from varios resources like ClassPath, FileSystem, etc.
No such support Provides generic way to load resources such as Image file
Loading multiple configuration files is not possible In large enterprise project, you have to load multiple configuration files. In that case, ApplicationContext is very good option
Eg.; new ClassPathXmlApplicationContext(new String[]{“confg-1”, “confg-2”, “confg-3”});

Download project

Spring Application using BeanFactory & ApplicationContext (3kB)

Happy Coding !!
Happy Learning !!

Spring Dependency Injection using Setter method