Java Programming Tutorials

Java programming tutorials with many code examples!

Spring properties file

Problem:

How to load properties file in Spring? In the following example we show how to use PropertySource class to load properties into Spring Application Context.

Solution:

In this post we’ll create a simple Sprint Boot application that will load properties file from classpath and inject into a bean.

To make things less verbose we’ll use Gradle to configure the project. Here’s our build.gradle with simple Spring Boot setup:

buildscript {
    repositories {
        jcenter()
        maven { url "http://repo.spring.io/snapshot" }
        maven { url "http://repo.spring.io/milestone" }
    }
    dependencies {
        // Provides tasks to create executable JAR and run project from source.
        // It also adds ResolutionStrategy, which allows to ommit versions in
        // "blessed" dependencies below.
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.3.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'spring-boot'

jar {
    baseName = 'spring-tutorial'
    version =  '0.0.1-SNAPSHOT'
}

repositories {
    jcenter()
    maven { url "http://repo.spring.io/snapshot" }
    maven { url "http://repo.spring.io/milestone" }
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter")
    testCompile("org.springframework.boot:spring-boot-starter-test")
}

In Gradle directory structure is the same as in Maven, so sources are in src/main/java and resources in src/main/resources. The code is straightforward:

package com.farenda.spring.tutorial;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.PropertySource;

@EnableAutoConfiguration
@PropertySource(
        // can be: classpath, classpath*, file:
        value = "classpath:my-app.properties"
        // Since Spring 4.0 - easies working with optional properties:
        //ignoreResourceNotFound = true
)
public class SpringLoadPropertiesFile {

    @Value("${databaseName}")
    private String databaseName;

    @Value("${connectionTimeout}")
    private long connectionTimeout;

    public static void main(String[] args) {
        ApplicationContext context =
                SpringApplication.run(SpringLoadPropertiesFile.class, args);

        SpringLoadPropertiesFile bean =
                context.getBean(SpringLoadPropertiesFile.class);

        System.out.printf("Database name: %s, connection timeout: %d%n",
                bean.databaseName, bean.connectionTimeout);
    }
}

We put sample my-app.properties file in the src/main/resources directory with the following content:

databaseName=books
connectionTimeout=1000

And here’s the output of running the application:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.2.3.RELEASE)

2015-08-31 19:31:35.704  INFO 10369 --- [           main] c.f.s.tutorial.SpringLoadPropertiesFile  : Starting SpringLoadPropertiesFile on namek with PID 10369 (/home/przemek/Dropbox/projekty/farenda/java/spring-boot-hello-world/build/classes/main started by przemek in /home/przemek/Dropbox/projekty/farenda/java/spring-boot-hello-world)
2015-08-31 19:31:35.766  INFO 10369 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@7a187f14: startup date [Mon Aug 31 19:31:35 CEST 2015]; root of context hierarchy
2015-08-31 19:31:37.254  INFO 10369 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2015-08-31 19:31:37.273  INFO 10369 --- [           main] c.f.s.tutorial.SpringLoadPropertiesFile  : Started SpringLoadPropertiesFile in 1.997 seconds (JVM running for 2.687)
Database name: books, connection timeout: 1000
2015-08-31 19:31:37.279  INFO 10369 --- [       Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@7a187f14: startup date [Mon Aug 31 19:31:35 CEST 2015]; root of context hierarchy
2015-08-31 19:31:37.280  INFO 10369 --- [       Thread-1] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

Simple, isn’t it? ;-)

New to Spring Boot? Check out Spring Boot Hello World!

Share with the World!