ZetCode

Spring bean reference tutorial

last modified July 9, 2020

Spring bean reference tutorial shows how to refer to beans in a XML configuration file in a Spring application.

Spring is a popular Java application framework for creating enterprise applications.

Spring ref attribute

The ref attribute is a shortcut to the <ref> tag, used to refer to other beans for injection.

Spring bean reference example

The application contains two beans: infoMessage and mesageRenderer. The mesageRenderer refers to the infoMessage via the ref attribute.

src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           │   Application.java
│   │           ├───bean
│   │           │       IMessage.java
│   │           │       InfoMessage.java
│   │           └───service
│   │                   MessageRenderer.java
│   └───resources
│           logback.xml
│           my-beans.xml
└───test
    └───java

This is the project structure.

pom.xml
<?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>com.zetcode</groupId>
    <artifactId>beanreference</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <spring-version>5.1.3.RELEASE</spring-version>

    </properties>

    <dependencies>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring-version}</version>
        </dependency>
        
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.6.0</version>
                <configuration>
                    <mainClass>com.zetcode.Application</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

In the pom.xml file, we have basic Spring dependencies spring-core and spring-context and logging logback-classic dependency.

The exec-maven-plugin is used for executing Spring application from the Maven on the command line.

resources/logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <logger name="org.springframework" level="ERROR"/>
    <logger name="com.zetcode" level="INFO"/>

    <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <Pattern>%d{HH:mm:ss.SSS} [%thread] %blue(%-5level) %magenta(%logger{36}) - %msg %n
            </Pattern>
        </encoder>
    </appender>

    <root>
        <level value="INFO" />
        <appender-ref ref="consoleAppender" />
    </root>
</configuration>

The logback.xml is a configuration file for the Logback logging library.

resources/my-beans.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
            http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="infoMessage" class="com.zetcode.bean.InfoMessage"/>

    <bean name="messageRenderer" class="com.zetcode.service.MessageRenderer">
            <constructor-arg name="message" ref="infoMessage"/>
    </bean>

</beans>

The my-beans.xml file declares two beans: info and messageRenderer. The infoMessage refers to the infoMessage via the ref attribute. Spring injects the infoMessage bean into the message attribute via constructor injection.

com/zetcode/bean/IMessage.java
package com.zetcode.bean;

public interface IMessage {

    String getMessage();
}

The IMessage interface has one method declaration.

com/zetcode/bean/InfoMessage.java
package com.zetcode.bean;

public class InfoMessage implements IMessage {

    public String getMessage() {

        return "This is information message";
    }
}

The InfoMessage bean returns an information message.

com/zetcode/service/MessageRenderer.java
package com.zetcode.service;

import com.zetcode.Application;
import com.zetcode.bean.IMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MessageRenderer {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    private IMessage message;

    public MessageRenderer(IMessage message) {
        this.message = message;
    }
    
    public void renderMessage() {

        logger.info("{}", message.getMessage());
    }
}

The MessageRenderer renders a message. It expects one bean to be injected. Spring injects the infoMessage bean into the MessageRenderer via constructor injection.

com/zetcode/Application.java
package com.zetcode;

import com.zetcode.service.MessageRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.GenericXmlApplicationContext;

public class Application {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {

        var ctx = new GenericXmlApplicationContext("my-beans.xml");
        var renderer =  (MessageRenderer) ctx.getBean("messageRenderer");

        renderer.renderMessage();

        ctx.close();
    }
}

This is the main application class. It retrieves the MessageRenderer bean and call its renderMessage() method.

$ mvn -q exec:java
12:05:23.567 [com.zetcode.Application.main()] INFO  com.zetcode.Application - This is information message

We run the application.

In this tutorial, we have shown how to refer to other beans with Spring's XML ref attribute.

List all Spring tutorials.