Spring XML Based Configuration Example

This tutorial shows you how to use Spring XML Based Configuration. We create a simple service called CoffeeMachine which will display a simple message to the console. We configure our application using XML Based configuration. Finally we create the spring ApplicationContext using the ClassPathXmlApplicationContext for bootstrapping the application.

Maven Dependencies

We need to add the spring-core and spring-context dependencies to our classpath.

<project xmlns="http://maven.apache.org/POM/4.0.0"
    <name>SPRING-CORE - ${project.artifactId}</name>



CoffeeMachine Service

This CoffeeMachine class is used to demonstrate how to use spring XML based configuration.

package com.memorynotfound.spring;

public class CoffeeMachine {

    public void makeCoffee(String beans) {
        System.out.println("Making " + beans + " coffee!");

Spring XML Based Configuration

Typically, a spring configuration consists of at least one and typically more than one bean definition that the container must manage. These beans are registered using the <bean> element inside a top-level <beans> element. These bean definitions correspond to the actual objects that make up your application. In this example we create a bean of type CoffeeMachine . We register this bean by creating a <bean> element and adding the fully qualified class name of the bean to the class attribute.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

        This tutorial demonstrates how to configure spring using XML based configuration

    <bean class="com.memorynotfound.spring.CoffeeMachine"/>


Bootstrapping Spring ApplicationContext

We bootstrap the ApplicationContext using the ClassPathXmlApplicationContext. We pass the location of our Spring XML Based Configuration using an array of strings. Next we obtain the spring managed bean by calling the getBean method, providing the class name. Finally we can call the makeCoffee method of the CoffeeMachine.

package com.memorynotfound.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Run {

    public static void main(String... args){
        ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"app-config.xml"});
        CoffeeMachine coffeeMachine = context.getBean(CoffeeMachine.class);


Making Java coffee!



You may also like...