/ Java

Spring Tutorials - Spring Context and Beans

Back to Spring Tutorials main page

Spring Logo

Overview

This tutorial will look at the very fundamentals of the Spring Framework; namely the IoC container using the Spring bean factory, the Spring application context and managed Spring beans.

The Spring container controls the lifecycle of the defined Spring beans, which means it will handle the tasks of creating, initializing, wiring and destroying the beans.

In the example below we will create a Java bean, define it as a Spring bean, load the bean definition into a running container and retrieve a bean from the container so that we can use it in our application. We will both look at using the more simple BeanFactory container and the now more typical ApplicationContext container (which subclasses the BeanFactory).

The steps we follow in this example are:

  1. Create Maven project for the example
  2. Create a simple Spring Bean class
  3. Create a Spring configuration XML file where we specify a definition for the bean
  4. Create a bootstrap class for starting a BeanFactory container
  5. Create a bootstrap class for starting an ApplicationContext container
  6. Start each of the containers, so they load the bean definitions from the configuration file
  7. Retrieve a bean from the container and use it in the application
The source code for this tutorial can be found on GitHub:
https://github.com/acntech/spring-tutorials/tree/develop/spring-context-tutorial

Setup

The example code was created using the following tools and frameworks:

We start out by creating a Maven project for our example, with the Spring dependency defined.

The Maven pom.xml file ends ut looking like this (example source code):

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>no.acntech.tutorials</groupId>
    <artifactId>spring-context-tutorial</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- PROPERTIES -->
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <slf4j.version>1.7.21</slf4j.version>
        <logback.version>1.1.7</logback.version>
        <spring.version>4.3.3.RELEASE</spring.version>
    </properties>

    <!-- DEPENDENCIES -->
    <dependencies>
        <!-- Logging -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <!-- Spring Framework -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
</project>

We get the familiar Maven project layout:

.
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── no
    │   │       └── acntech
    │   │           └── tutorial
    │   │               └── spring
    │   │                   ├── bean
    │   │                   │   └── SimpleSpringBean.java
    │   │                   ├── BootstrapApplicationContext.java
    │   │                   └── BootstrapBeanFactory.java
    │   └── resources
    │       ├── logback.xml
    │       └── spring.xml
    └── test
        └── java

Example

We start by creating a simple Spring bean class.

package no.acntech.tutorial.spring.bean;

public class SimpleSpringBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(SimpleSpringBean.class);

    private String message;

    public SimpleSpringBean() {
        LOGGER.info("Bean created");
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

Next we need to create the Spring configuration file where the declaration of the Spring Bean will be defined.

<?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
    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">

    <bean id="simpleSpringBean" class="no.acntech.tutorial.spring.bean.SimpleSpringBean">
        <property name="message" value="Hello World!"/>
    </bean>
</beans>

Here we see that we can set object fields in the Spring Bean in the configuration file, and this will be wired together when the container instantiates a new bean. In this case we assign a value to a string variable, but this can be any type of object. Even other Spring Beans, which we will see in the next tutorial.

Now we need to create a bootstrap main method so that we can start a container. First we look at starting a BeanFactory container.

package no.acntech.tutorial.spring;

import no.acntech.tutorial.spring.bean.SimpleSpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;

public class BootstrapBeanFactory {

    private static final Logger LOGGER = LoggerFactory.getLogger(BootstrapBeanFactory.class);

    public static void main(String[] args) {
        LOGGER.info("Bootstrapping Spring Bean Factory");

        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
        int beanDefinitionsFound = beanDefinitionReader.loadBeanDefinitions("spring.xml");
        LOGGER.info("{} Spring Bean definitions loaded from spring.xml", beanDefinitionsFound);

        SimpleSpringBean simpleSpringBean = beanFactory.getBean(SimpleSpringBean.class);
        LOGGER.info("Spring says: {}", simpleSpringBean.getMessage());
    }
}

If we run the main method in this class we get the following output:

2016-10-22 08:42:19,303 [main] INFO  n.a.t.spring.BootstrapBeanFactory - Bootstrapping Spring Bean Factory
2016-10-22 08:42:19,601 [main] INFO  n.a.t.spring.bean.SimpleSpringBean - Bean created
2016-10-22 08:42:19,676 [main] INFO  n.a.t.spring.BootstrapBeanFactory - 1 Spring Bean definitions loaded from spring.xml
2016-10-22 08:42:19,722 [main] INFO  n.a.t.spring.BootstrapBeanFactory - Spring says: Hello World!

We see that the container creates a Spring bean from the definition, and we get the expected log output.

Now we do the same using the ApplicationContext container. The bootstrap main method look like this:

package no.acntech.tutorial.spring;

import no.acntech.tutorial.spring.bean.SimpleSpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BootstrapApplicationContext {

    private static final Logger LOGGER = LoggerFactory.getLogger(BootstrapApplicationContext.class);

    public static void main(String[] args) {
        LOGGER.info("Bootstrapping Spring Application Context");

        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        int beansFound = context.getBeanDefinitionCount();
        LOGGER.info("{} Spring Bean definitions loaded from spring.xml", beansFound);

        SimpleSpringBean simpleSpringBean = context.getBean(SimpleSpringBean.class);
        LOGGER.info("Spring says: {}", simpleSpringBean.getMessage());
    }
}

Using the implementation ClassPathXmlApplicationContext we can load bean definitions from an XML file in the same way as we did with the DefaultListableBeanFactory.

Running this class we get the log output:

2016-10-22 09:49:08,927 [main] INFO  n.a.t.s.BootstrapApplicationContext - Bootstrapping Spring Application Context
2016-10-22 09:49:09,398 [main] INFO  n.a.t.spring.bean.SimpleSpringBean - Bean created
2016-10-22 09:49:09,475 [main] INFO  n.a.t.s.BootstrapApplicationContext - 1 Spring Bean definitions loaded from spring.xml
2016-10-22 09:49:09,480 [main] INFO  n.a.t.s.BootstrapApplicationContext - Spring says: Hello World!

The result is the same as with the BeanFactory, as we expected.

Back to Spring Tutorials main page