Home > Books > How It Works

How It Works

Instantiating an Application Context

    ApplicationContext is an interface only. You have to instantiate an implementation of it. The ClassPathXmlApplicationContext implementation builds an application context by loading an XML configuration file from the classpath. You can also specify multiple configuration files for it.

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

    Besides ClassPathXmlApplicationContext, several other ApplicationContext implementations are provided by Spring. FileSystemXmlApplicationContext is used to load XML configuration files from the file system or from URLs, while XmlWebApplicationContext and XmlPortletApplicationContext can be used in web and portal applications only.

Getting Beans from the IoC Container

    To get a declared bean from a bean factory or an application context, you just make a call to the getBean() method and pass in the unique bean name. The return type of the getBean() method is java.lang.Object, so you have to cast it to its actual type before using it.

SequenceGenerator generator = (SequenceGenerator) context.getBean("sequenceGenerator");

    Up to this step, you are free to use the bean just like any object you created using a constructor. The complete source code for running the sequence generator application is given in the following Main class:

package com.apress.springrecipes.sequence;

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

public class Main {

    public static void main(String[] args) {

        ApplicationContext context =
            new ClassPathXmlApplicationContext("beans.xml");

        SequenceGenerator generator =
            (SequenceGenerator) context.getBean("sequenceGenerator");

        System.out.println(generator.getSequence());
        System.out.println(generator.getSequence());
    }
}
Categories: Books
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment