Spring ClassPathXmlApplicationContext


Spring provides two types of containers:

  • BeanFactory: It supports bean instantiating and wiring
  • ApplicationContext: It extends the BeanFactory and so provides all those features as that a BeanFactory. Additionally, it provides automatic registration of BeanPostProcessor, internationalization, and many more features

The Spring container is responsible for instantiating and managing the lifecycle of Spring beans. The ClassPathXmlApplicationContext is a class that implements the org.springframework.context.ApplicationContext interface.

In this quick tutorial, we’ll learn how to work with ClassPathXmlApplicationContext.

Initial Setup:

Let’s say we have a Java class named Person:

Also, let’s define the bean in our applicationContext.xml:

Working With ClassPathXmlApplicationContext:

When using ClassPathXmlApplicationContext, the container loads the bean definitions from the given xml file present in our CLASSPATH.

Now that we have defined the Person bean in our application context, let’s use it to load beans in our main() method:

Note that we can also use several XML configuration files to initialize our Spring container:

In such a case, later bean definitions will override the ones defined in the earlier loaded files.

The classpath*: Prefix:

While constructing an xml defined application context, we may use the classpath*: prefix at times:

This prefix specifies that all the classpath resources with the given name must be merged together to form the final application context definition.

Registering a ShutDownHook:

The WebApplicationContext already has a code for shutting down the IoC container properly.

However, for any non-web Spring application, we must use registerShutdownHook() method to shut down the Spring IoC container gracefully during application shutdown. We can define the pre-destroy methods for our beans that’ll be invoked for releasing all held resources.

Let’s add a method in our Person class:

And update our applicationContext.xml:

When using annotations, we could have used @PreDestroy annotation over the method instead of configuring that in the xml.

Let’s now register the shutdown hook to our ApplicationContext:

The above code on execution will print:


In this article, we learned the basic usage of ClassPathXmlApplicationContext.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *