How to load spring application context xml from classpath in java - Java @ Desk

Friday, June 28, 2013

How to load spring application context xml from classpath in java

This article will explain you how to load a spring configuration/application context xml file in standalone java application.
ApplicationContext is an interface that is being implemented in Spring to load a spring configuration in a java class. The ClassPathXmlApplicationContext class implements this interface which takes a path to the spring configuration application context xml file located in a classpath.
Below is the sample implementation to load a xml file and load a bean from that xml file in java.

import org.springframework.context.ApplicationContext;  
 import org.springframework.context.support.ClassPathXmlApplicationContext;  
 public class SpringLoadAppContext {  
   private static final String[] SPRING_CONFIG_FILES = new String[] { "CLASSPATH_APP_CONTEXT_XML_FILE_1",  
       "CLASSPATH_APP_CONTEXT_XML_FILE_2", "CLASSPATH_APP_CONTEXT_XML_FILE_3" };  
   private static final String CLASSPATH_APP_CONTEXT_XML_FILE_1 = "classpath:PATH_TO_XML_FILE";  
   public static void main(String args[]) {  
     // Load SINGLE application context xml file  
     ApplicationContext applicationContext = new ClassPathXmlApplicationContext("CLASSPATH_APP_CONTEXT_XML_FILE");  
     // Load a bean from application context  
     Object object = applicationContext.getBean("BEAN_ID");  
     // Load MULTIPLE application context xml file  
     ApplicationContext multipleAppContext = new ClassPathXmlApplicationContext(SPRING_CONFIG_FILES);  
   }  
 }  
As you can see in the above implementation, we can load multiple spring configuration files at once.

Once the configuration file is loaded, a bean can be loaded using the applicationContext.getBean("BEAN_ID"); where BEAN_ID is the bean id that is configured in the xml file.

Eager loading of bean in spring java
By default, spring instantiates all the beans once the file gets loaded using the ClassPathXmlApplicationContext. This is known as eager loading of spring beans.
If you want to do a lazy loading of a bean, where the bean will be instantiated only when first client request is received for that bean i.e. applicationContext.getBean() gets called for particular bean then do some modification in the configuration file as shown below








No comments:

Post a Comment