Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 119 ยท Spring Framework

Spring XML Configuration, BeanFactory and ApplicationContext

Read and write Spring's classic beans.xml - property and constructor injection, autowire modes, init and destroy methods - and learn how BeanFactory differs from ApplicationContext.

Before annotations and Java configuration, every Spring application described its beans in an XML file. Many large codebases still do, banks and insurance systems especially, and Spring Framework 7 still reads these files. Even if you never write one, you will read them in older projects, in tutorials, and in the Spring reference documentation, so it pays to know what the tags mean.

In this lesson you will learn the structure of beans.xml, how setter injection and constructor injection look in XML, what the autowire modes do, how init-method and destroy-method hook into the lifecycle, and how the different application context classes load configuration. You will also see the difference between a BeanFactory and an ApplicationContext. Spring itself can't run on this page, so the examples are real Spring code shown read-only, plus a small runnable container written in plain Java that follows the same steps. Read Beans, Configuration and Component Scanning first, because everything here has an annotation-based twin there.

What a beans.xml file looks like

The root element is <beans>. Inside it, each <bean> tag is one bean definition: a recipe that tells the container which class to instantiate and how to wire it.

XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="clock" class="com.example.shop.Clock"/>

    <bean id="mailer" class="com.example.shop.Mailer"
          init-method="connect" destroy-method="disconnect">
        <property name="host" value="smtp.example.com"/>   <!-- setHost("smtp.example.com") -->
        <property name="port" value="587"/>                <!-- setPort(587), converted to int -->
    </bean>

    <bean id="greeter" class="com.example.shop.Greeter">
        <constructor-arg value="Welcome"/>                 <!-- first constructor parameter -->
        <constructor-arg ref="clock"/>                     <!-- a reference to another bean -->
    </bean>

    <bean id="basket" class="com.example.shop.Basket" scope="prototype"/>
</beans>

The pieces map directly onto Java:

XML Meaning
id, class The bean name and the class the container instantiates (with its no-argument constructor unless you add constructor-arg)
<property name="host" value="..."> Setter injection: calls setHost(...). Spring converts the text to the setter's parameter type
<property name="clock" ref="clock"> Setter injection of another bean, by that bean's id
<constructor-arg> Constructor injection. Add index="0" or name="greeting" when the order is unclear
scope singleton (the default), prototype, or a web scope such as request
init-method, destroy-method Methods called after injection and when the context closes
lazy-init="true" Do not create this singleton at startup

Collections and nested beans are written with <list>, <set>, <map> and inner <bean> tags inside a <property>. Large files can be split up with <import resource="security-beans.xml"/>.

Loading the file

You hand the file name to an application context class and ask it for beans:

Java
public static void main(String[] args) {
    try (var context = new ClassPathXmlApplicationContext("beans.xml")) {   // searches the classpath
        Greeter greeter = context.getBean("greeter", Greeter.class);
        System.out.println(greeter.greet("Ana"));
    }                                                                        // close() runs destroy methods
}

ClassPathXmlApplicationContext is the container you will meet most often. The following runnable program is not Spring. It is a small container that parses the very same kind of XML with the JDK's own parser, creates objects with reflection, applies setters and constructor arguments, honors scope, init-method and destroy-method, and creates all singletons when it starts. Those are the steps a real context performs, in miniature (the Main$Clock class names are how Java writes a class nested inside Main).

Java A miniature XML application context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at the order of the output. The mailer connects during refresh, before anyone asked for it, because singletons are created eagerly. greeter received clock through its constructor, and mailer is the same object on both calls. The two baskets are different objects because a prototype is created on every request. The destroy callback ran only because the program closed the context. Forgetting close() is a common reason why destroy-method seems not to run (a JVM shutdown hook can do it for you: context.registerShutdownHook()).

Autowiring in XML

Writing a ref for every property gets repetitive. The autowire attribute asks the container to fill in the dependencies itself:

Mode What Spring does
no (default) Nothing. Only explicit <property> and <constructor-arg> tags count
byName For each setter, looks for a bean whose id equals the property name (setMailer needs a bean named mailer)
byType For each setter, looks for one bean of the parameter's type. No match leaves the property unset, several matches fail with NoUniqueBeanDefinitionException
constructor Like byType, but for the parameters of the constructor with the most arguments that Spring can satisfy
XML
<bean id="notifier" class="com.example.shop.Notifier" autowire="byType"/>
<bean id="reporter" class="com.example.shop.Reporter" autowire="constructor"/>

When two beans have the same type, you can mark one with primary="true", or exclude one with autowire-candidate="false". Explicit properties always win over autowiring. The old autodetect mode was removed in Spring 3. In new code, prefer constructor injection with annotations: it makes dependencies visible in the class itself, and the XML file can't hide a missing one.

BeanFactory versus ApplicationContext

Spring has two container interfaces:

  • BeanFactory is the bare container. It knows bean definitions, creates beans on demand (lazily) and injects dependencies. The usual implementation is DefaultListableBeanFactory.
  • ApplicationContext extends BeanFactory and adds what real applications need: it pre-instantiates all non-lazy singletons at startup, detects BeanPostProcessor and other infrastructure beans automatically, handles annotations such as @Autowired and @Transactional, publishes and listens to events, resolves messages for internationalization (MessageSource), loads resources, and exposes the Environment with profiles and properties.

In application code you use ApplicationContext (or Spring Boot, which creates one for you). The old XmlBeanFactory class that people used to demonstrate the bare container is gone from current Spring versions. If you ever need a bare container, you build it from DefaultListableBeanFactory and an XmlBeanDefinitionReader.

The most important practical difference is when mistakes show up. The next program has two Mailer beans, so autowiring byType is ambiguous. It runs the same configuration in lazy mode (like a bare factory) and in eager mode (like an application context), and it also shows the three autowire modes working when there is only one Mailer:

Java Lazy factory versus eager context, plus the autowire modes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The lazy factory happily created clock and the byName notifier. The ambiguous bean only failed when somebody asked for it, perhaps in production, hours after startup. The eager context created beans in definition order and failed the moment the container started, before any request was served, which is where you want a wiring mistake to appear. This is the main reason why the eager default is such a good one. Use lazy-init="true" (or @Lazy) only for beans that are expensive and rarely used.

The ApplicationContext implementations

All of them do the same job. Only the source of the configuration differs:

Class Reads its configuration from
ClassPathXmlApplicationContext An XML file on the classpath ("beans.xml")
FileSystemXmlApplicationContext An XML file at a path on disk ("/etc/shop/beans.xml")
AnnotationConfigApplicationContext @Configuration and @Component classes (new AnnotationConfigApplicationContext(AppConfig.class))
GenericApplicationContext Whatever you register by hand, often combined with a reader class; mostly used in tests and frameworks
AnnotationConfigServletWebServerApplicationContext What Spring Boot creates for a servlet web application

XML and annotations mix freely. An annotation-based project can pull in a legacy file with @ImportResource("classpath:legacy-beans.xml") on a @Configuration class. An XML project can turn on annotation processing with <context:annotation-config/>, and component scanning with <context:component-scan base-package="com.example.shop"/>. That is a sensible migration path: move one package at a time to annotations and leave the rest of the XML alone.

When you read an unfamiliar XML configuration, start from the class attributes. Open each class and see which setters and constructors it has. The XML is only the wiring diagram. All behavior lives in the classes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A bean definition has <property name="port" value="587"/>. What does Spring do with it?

    A property element means setter injection. Spring converts the text value to the type of the setter parameter, here an int.
  2. 2. Two beans of type Mailer exist. A third bean uses autowire="byType" with a setMailer method. What happens when the context starts?

    byType needs exactly one candidate. Mark one bean primary="true", exclude the other with autowire-candidate="false", or use byName or an explicit ref.
  3. 3. What is the practical difference between BeanFactory and ApplicationContext when singleton beans are defined?

    A bare BeanFactory creates beans lazily when they are requested. ApplicationContext pre-instantiates singletons and adds events, message sources, annotation support and more.
  4. 4. A destroy-method never runs in a small main program. What is the most likely cause?

    Destroy callbacks run when the context closes. Use try-with-resources, call close(), or register a shutdown hook.

Summary

  • A beans.xml file is a list of <bean> definitions: a class, an id, and the wiring through <property> (setters) and <constructor-arg> (constructor).
  • scope, init-method, destroy-method, lazy-init and primary correspond to annotations like @Scope, @PostConstruct, @PreDestroy, @Lazy and @Primary.
  • autowire can be no, byName, byType or constructor. Ambiguity with byType fails with NoUniqueBeanDefinitionException.
  • BeanFactory is the minimal, lazy container. ApplicationContext adds eager singletons, post-processors, events, messages and the environment, and is what you use.
  • The context classes differ in where the configuration comes from: classpath XML, a file path, annotated classes, or Spring Boot's web context. @ImportResource and <context:component-scan> let XML and annotations coexist.
  • Destroy callbacks only run when the context is closed.

Next: Spring Expression Language shows the expression syntax you can use in value attributes and annotations.