Ebooks

Spring profile XML tutorial

Spring profile XML tutorial shows how to configure profiles in XML for a Spring application.

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

Spring profile

A profile is a named set of beans declared for a specific environment such as development or production. Profiles can be configured in XML or using annotations.

Spring profile example

The application defines two profiles: production and development.

pom.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │               Application.java
│   └───resources
│           database-dev.properties
│           database-prod.properties
│           logback.xml
└───test
    └───java

This is the project structure. We have two property files: database-dev.properties and database-prod.properties.

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>profileex</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>      

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</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, spring-context, spring-jdbc, 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} %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/database-dev.properties
db.url=jdbc:h2:mem:testdb
db.username=testuser
db.password=s$cret

These are development properties.

resources/database-prod.properties
db.url=jdbc:postgresql://localhost/mydb
db.username=user7
db.password=s$cret

These are production properties.

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"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath:database-${spring.profiles.active}.properties"/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
        <property name="url" value="${db.url}"/>
        <property name="username" value="${db.username}"/>
        <property name="password" value="${db.password}"/>
    </bean>

</beans>

The my-beans.xml contains a dataSource bean. The <context:property-placeholder> tag configures properties for the datasource, based on the active Spring profile.

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;

public class Application {

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

    public static void main(String[] args) {

        System.setProperty("spring.profiles.active", "prod");

        var ctx = new GenericXmlApplicationContext("my-beans.xml");

        var dataSource = (SimpleDriverDataSource) ctx.getBean("dataSource");

        logger.info("Url: {}", dataSource.getUrl());
        logger.info("User name: {}", dataSource.getUsername());
        logger.info("Password: {}", dataSource.getPassword());

        ctx.close();
    }
}

The application retrieves the dataSource bean and prints its properties. The active property is set with System.setProperty() method. Alternatively, we can set the property as a VM variable -Dspring.profiles.active=prod or in IDE settings.

$ mvn -q -Dspring.profiles.active=dev exec:java
20:30:45.832 INFO  com.zetcode.Application - Url: jdbc:h2:mem:testdb
20:30:45.832 INFO  com.zetcode.Application - User name: testuser
20:30:45.832 INFO  com.zetcode.Application - Password: s$cret

We run the application with the profile set on the command line

In this tutorial, we have created a development and production profile for a Spring application.

You might also be interested in these related tutorials: Spring @Bean annotation tutorial, Spring Singleton scope bean, Spring @ComponentScan tutorial, Spring inject List XML tutorial, Spring BeanDefinitionBuilder tutorial, Spring HikariCP tutorial, and Java tutorial.