How to load a Spring application context file from a standalone Java application

By Alvin J. Alexander, devdaily.com

Here's the source code for a standalone Java application where I load a Spring application context file with the ClassPathXmlApplicationContext method. In other blogs I've shown how to load the application context for web applications, but I also wanted to show how to do this for a standalone program.

Here's a source code for my Java program that loads a Spring application context file from the typical main method:

package com.devdaily.springtest1;

import com.devdaily.springtest1.dao.FileEventDao;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main
{

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

  public Main()
  {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    FileEventDao fileEventDao = (FileEventDao)ctx.getBean("fileEventDao");
    fileEventDao.doInsert(fileEventType);
  }

}

The application context file

That Java code showed how to load an application context file. It may also help to see what this context file looks like:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

  <bean id="fileEventDao" class="com.devdaily.springtest1.dao.FileEventDao">
    <property name="dataSource" ref="basicDataSource"/>
  </bean>

  <bean id="basicDataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost/my_database" />
    <property name="username" value="my_username" />
    <property name="password" value="my_password" />
    <property name="initialSize" value="5" />
    <property name="maxActive" value="10" />
  </bean>

</beans>

The Spring ClassPathXmlApplicationContext class

Because I use Spring's ClassPathXmlApplicationContext method to load my applicationContext.xml file, the only thing I have to do when I deploy my application is to make sure the applicationContext.xml file is in my classpath when I run my application. A simple way to do this is to put the applicationContext.xml in the same directory hierarchy where your compiled Java classes (i.e., your *.class files) are located.


devdaily logo