Ebooks

Spring BeanDefinitionBuilder tutorial

Spring BeanDefinitionBuilder tutorial shows how to programatically create new Spring beans using BeanDefinitionBuilder.

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

BeanDefinitionBuilder

BeanDefinitionBuilder is used to create new Spring beans programatically. It utilizes the builder pattern.

Spring BeanDefinitionBuilder example

The application creates create a simple string bean.

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>beanbuilderex</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.

src/main/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.

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "com.zetcode")
public class Application {

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

    public static void main(String[] args) {

        var ctx = new AnnotationConfigApplicationContext(Application.class);

        var beanFactory = (BeanDefinitionRegistry) ctx.getBeanFactory();

        beanFactory.registerBeanDefinition("myBean",
                BeanDefinitionBuilder.genericBeanDefinition(String.class)
                        .addConstructorArgValue("This is my bean")
                        .setScope("prototype")
                        .getBeanDefinition()
        );

        logger.info("{}", ctx.getBean("myBean"));

        ctx.close();
    }
}

The example creates a simple bean of type String using BeanDefinitionBuilder.

var beanFactory = (BeanDefinitionRegistry) ctx.getBeanFactory();

A bean factory is retrieved from the application context with getBeanFactory().

beanFactory.registerBeanDefinition("myBean",
    BeanDefinitionBuilder.genericBeanDefinition(String.class)
            .addConstructorArgValue("This is my bean")
            .setScope("prototype")
            .getBeanDefinition()
);

We register a new bean with registerBeanDefinition().

logger.info("{}", ctx.getBean("myBean"));

We get the bean from the application context with getBean() and log it.

$ mvn -q exec:java
20:51:05.970 [com.zetcode.Application.main()] INFO com.zetcode.Application - This is my bean    

We run the application.

In this tutorial, we have used the BeanDefinitionBuilder to register a new Spring bean programatically.

You might also be interested in these related tutorials: Spring inject List XML tutorial, JdbcTemplate in a classic Spring application, Spring Singleton scope bean, Spring HikariCP tutorial, and Java tutorial.