Spring provides two types of containers:
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.
Let’s say we have a Java class named Person:
public class Person { private int id; private String name; ... }
<bean id="person" class="com.programmergirl.domain.Person"> <property name="id" value="1"/> <property name="name" value="Sam"/> </bean>
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:
public class MyApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Person person = (Person) context.getBean("person"); System.out.println(person.getId() + ":" + person.getName()); } }
ApplicationContext context = new ClassPathXmlApplicationContext("appContext1.xml", "appContext2.xml");
While constructing an xml defined application context, we may use the classpath*: prefix at times:
ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:appContext.xml");
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:
public class Person { ... public void preDestroy() { System.out.println("Releasing all resources"); } }
<bean id="person" class="com.programmergirl.domain.Person" destroy-method="preDestroy"> <property name="id" value="1"/> <property name="name" value="Sam"/> </bean>
Let’s now register the shutdown hook to our ApplicationContext:
public class MyApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Person person = (Person) context.getBean("person"); System.out.println(person.getId() + ":" + person.getName()); context.registerShutdownHook(); } }
1:Sam Releasing all resources
In this article, we learned the basic usage of ClassPathXmlApplicationContext.