Java Reference
In-Depth Information
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 , there are several other ApplicationContext
implementations provided by Spring. FileSystemXmlApplicationContext is used to load
XML configuration files from the file system, 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.springenterpriserecipes.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");
Search WWH ::




Custom Search