The ClassPathXmlApplicationContext is a class in the Spring Framework that is used to load and configure the application context based on an XML configuration file located in the classpath. It is one of the Spring’s ApplicationContext implementations, which provides an advanced container for managing beans and their lifecycle. Spring Boot and newer versions of Spring favour annotations and Java-based configurations for simplicity and flexibility.

ApplicationContext context = new ClassPathXmlApplicationContext();
  • XML Configuration
    • It loads beans and their configurations from an XML file(s), typically named applicationContext.xml in the classpath.
  • ClassPath:
    • The configuration XML file must be available in the classpath. The resources folder is a common and recommended location where it should reside.
  • Implementation of ApplicationContext
    • It extends the AbstractApplicationContext class and implements the ConfigurableApplicationContext interface, providing additional lifecycle and configuration capabilities.
  • Dependency Injection
    • The container resolves dependencies and injects them into the defined beans based on the XML configuration.

Advantages of ClassPathXmlApplicationContext

  • Centralised Configuration
    • The XML file provides a single place to define all bean configurations.
  • Standardised Format
    • XML files can be easier to standardise and validate compared to annotations.
  • Externalised Configuration
    • XML files can be updated without modifying the source code.

Create XML configuration

You have to create the XML configuration file in the classpath, in this example we name the configuration file applicationContext.xml.

  1. Define bean
<?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 definitions here -->
 
</beans>

  1. Create your bean tag You have to mention the name of the bean (id) and the class. Spring will retrieve the bean using the id when you call the context.getBean("person") in the main application. Here you have to define the id and mention the fully qualified class name.
	<!-- bean definitions here -->
	<bean id="person" class="com.example.Person">
	</bean>

  1. Initialise the ApplicationContext Use ClassPathXmlApplicationContext to load the XML file and retrieve beans. Here you will cast the bean by its type as the method returns an Object type.
package com.example;  
  
import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
  
public class App {  
    public static void main(String[] args) {  
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
        Person p1 = (Person) context.getBean("person");  
        p1.code();  
    }  
}
package com.example;  
  
public class Person {  
    public void code() {  
        System.out.println("Coding...");  
    }  
}
Coding...

Spring bean

Bean creation

The Spring IoC container is initialised when this line is executed:

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

At this point, the XML configuration file (applicationContext.xml) is loaded. The Spring container scans the XML file, initialises the context, and create the beans mentioned in the XML file (those tagged with <bean></bean>). But only those beans defined with a singleton scope are created immediately during context initialisation. Beans defined with a prototype scope or marked for lazy initialisation are created later, typically when they are explicitly requested.

Spring will still create the object even if you don’t mention a bean id in the XML configuration.

<bean class="com.example.Person" />

If a bean definition does not specify an id, Spring automatically generates an internal ID for the bean. You can still retrieve this bean using its type (if it’s unique using T getBean(Class<T> requiredType)) or by explicitly requesting the generated ID (not commonly done).

Person p1 = context.getBean(Person.class); 

Get bean

The BeanFactory interface in Spring provides various getBean() methods to retrieve beans from the IoC container.

MethodDescription
Object getBean(String name)Retrieves a bean by name. Returns the object type (type casting may be required).
T getBean(String name, Class<T> requiredType)Retrieves a bean by name and type. Returns the specific type.
T getBean(Class<T> requiredType)Retrieves a bean by type (throws error if multiple). Returns the specific type.

If multiple beans of the same type exist, using the T getBean(Class<T> requiredType) method Spring will throw a NoUniqueBeanDefinitionException. You can resolve the issue using primary bean (More in Primary bean).

Scope

Scope refers to the lifecycle and visibility of a bean. It defines how and when the bean is created, how long it lives, and how it is shared within the application.

ScopeWhen to Use
Singleton (Default)Use for stateless, reusable objects (e.g., service or DAO beans).
PrototypeUse for stateful or temporary objects.
Request (Web App)Use for request-specific data in web applications.
Session (Web App)Use for session-specific data in web applications.
Application (Web App)Use for application-wide single instances in web applications.

Singleton

A single instance of the bean is created and shared across the entire Spring container. There is only one instance exists for the application context. It is the default scope when you don’t explicitly define the scope of a bean. Every time the getBean() is called on a bean defined with singleton scope, the same object is returned.

Lifecycle: It is created when the application context is initialised and destroyed when the context is closed.

<bean id="myBean" class="com.example.MyBean" scope="singleton" />
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 
MyBean bean1 = context.getBean("myBean"); 
MyBean bean2 = context.getBean("myBean"); 
 
System.out.println(bean1 == bean2);
true

Prototype

A new instance of the bean is created every time it is requested from the Spring container. Multiple instances can exist, and the container does not track them after creation.

Lifecycle: Created when requested (via getBean()), not managed after initialisation (i.e., Spring does not handle its destruction).

<bean id="myBean" class="com.example.MyBean" scope="prototype" />
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 
MyBean bean1 = context.getBean("myBean"); 
MyBean bean2 = context.getBean("myBean"); 
 
System.out.println(bean1 == bean2);
false

Lazy-initialisation

By default, Spring creates all singleton beans as part of the initialisation process. Generally, this pre-instantiation is desirable, because errors in the configuration or surrounding environment are discovered immediately, as opposed to hours or even days later. When this behaviour is not desirable, you can prevent pre-instantiation of a singleton bean by marking the bean definition as being lazy-initialised.  A lazy-initialised bean tells the IoC container to create a bean instance when it is first requested, rather than creating them when the ApplicationContext starts.  To mark a bean as lazy-initialised bean, you add the lazy-init attribute to its bean definition and set it to true.

<bean id="person" class="com.example.Person" lazy-init="true"/>
public class Person {  
    public Person() {  
        System.out.println("Person object created");  
    }  
}
public class App {  
    public static void main(String[] args) {  
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
    }  
}

When the Person bean is defined as lazy-initialised bean, the object will not be created upon the start of IoC container. The object will only be created when requested.

public class App {  
    public static void main(String[] args) {  
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
        Person p1 = (Person) context.getBean("person");
    }  
}
Person object created

However, when a lazy-initialised bean is a dependency of a singleton bean that is not lazy-initialised, the ApplicationContext creates the lazy-initialised bean at startup, because it must satisfy the singleton’s dependencies. The lazy-initialised bean is injected into a singleton bean elsewhere that is not lazy-initialised.

You can also control lazy-initialisation for a set of beans by using the using the default-lazy-init attribute on the <beans/> element.

<beans default-lazy-init="true"> 
	<!-- No bean will be pre-instantiated... --> 
	
</beans>

Bean aliasing

In a bean definition itself, you can supply more than one name for the bean. These names can be equivalent aliases to the same bean and are useful for some situations, such as letting each component in an application refer to a common dependency by using a bean name that is specific to that component itself.

Name attribute

You can specify the alias in the name attribute, separated by a comma (,), semicolon (;), or white space.

<bean id="mainBean" class="com.example.MyBean" name="alias1 alias2 alias3" />

In this example, the bean mainBean can also be referred to as alias1, alias2, or alias3.

MyBean bean1 = (MyBean) context.getBean("mainBean");
MyBean bean2 = (MyBean) context.getBean("alias1");
MyBean bean3 = (MyBean) context.getBean("alias2");

Alias tag

<bean id="mainBean" class="com.example.MyBean" />
<alias name="mainBean" alias="alias1" />
<alias name="mainBean" alias="alias2" />
<alias name="mainBean" alias="alias3" />

In this example, alias1, alias2, and alias3 are additional names for the mainBean.


Back to parent page: Spring

Web_and_App_Development Programming_Languages Java Spring_Framework XML_Based_Configuration Spring_Bean Bean_Scope Lazy_Initialisation Bean_Aliasing

Reference: