Spring @PropertySourceの例

Spring @PropertySourceの例

spring-properties-example

Springでは、@PropertySourceアノテーションを使用して、構成をプロパティファイルに外部化できます。 このチュートリアルでは、@PropertySourceを使用してプロパティファイルを読み取り、@ValueEnvironmentで値を表示する方法を示します。

P.S @PropertySource has been available since Spring 3.1

1. @PropertySourceおよび@Value

古典的な例として、プロパティファイルを読み取り、${}で表示します。

config.properties

mongodb.url=1.2.3.4
mongodb.db=hello

AppConfigMongoDB

package com.example.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
//...

@Configuration
@ComponentScan(basePackages = { "com.example.*" })
@PropertySource("classpath:config.properties")
public class AppConfigMongoDB {

    //1.2.3.4
    @Value("${mongodb.url}")
    private String mongodbUrl;

    //hello
    @Value("${mongodb.db}")
    private String defaultDb;

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {

        MongoClientOptions mongoOptions =
            new MongoClientOptions.Builder().maxWaitTime(1000 * 60 * 5).build();
        MongoClient mongo = new MongoClient(mongodbUrl, mongoOptions);
        MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongo, defaultDb);
        return new MongoTemplate(mongoDbFactory);

    }

    //To resolve ${} in @Value
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

Note
@Valuesの$ \ {}を解決するには、XMLまたは注釈構成ファイルのいずれかに静的PropertySourcesPlaceholderConfigurerを登録する必要があります。

2. @PropertySourceと環境

Springは、Environmentを使用してプロパティ値を取得することをお勧めします。

AppConfigMongoDB

package com.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
//...

@Configuration
@ComponentScan(basePackages = { "com.example.*" })
@PropertySource("classpath:config.properties")
public class AppConfigMongoDB {

    @Autowired
    private Environment env;

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {

        String mongodbUrl = env.getProperty("mongodb.url");
        String defaultDb = env.getProperty("mongodb.db");

        MongoClientOptions mongoOptions =
            new MongoClientOptions.Builder().maxWaitTime(1000 * 60 * 5).build();
        MongoClient mongo = new MongoClient(mongodbUrl, mongoOptions);
        MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongo, defaultDb);
        return new MongoTemplate(mongoDbFactory);

    }

}

3. @PropertySourceのその他の例

より一般的な例。

3.1 Example to resolve $\{} within @PropertySource resource locations.

    @Configuration
    @PropertySource("file:${app.home}/app.properties")
    public class AppConfig {
        @Autowired
        Environment env;
    }

起動時にシステムプロパティを設定します。

    System.setProperty("app.home", "test");

    java -jar -Dapp.home="/home/mkyon/test" example.jar

3.2 Include multiple properties files.

    @Configuration
    @PropertySource({
        "classpath:config.properties",
        "classpath:db.properties" //if same key, this will 'win'
    })
    public class AppConfig {
        @Autowired
        Environment env;
    }


プロパティキーが重複している場合、最後に宣言されたファイルが「勝ち」、オーバーライドされます。

4. Spring 4および@PropertySources

Spring 4のいくつかの機能強化。

4.1 Introduces new @PropertySources to support Java 8 and better way to include multiple properties files.

    @Configuration
    @PropertySources({
        @PropertySource("classpath:config.properties"),
        @PropertySource("classpath:db.properties")
    })
    public class AppConfig {
        //...
    }

4.2 Allow @PropertySource to ignore the not found properties file.

    @Configuration
    @PropertySource("classpath:missing.properties")
    public class AppConfig {
        //...
    }

missing.propertiesが見つからない場合、システムは起動できず、FileNotFoundExceptionをスローします

    Caused by: java.io.FileNotFoundException:
        class path resource [missiong.properties] cannot be opened because it does not exist

Spring 4では、ignoreResourceNotFoundを使用して、見つからないプロパティファイルを無視できます。

    @Configuration
    @PropertySource(value="classpath:missing.properties", ignoreResourceNotFound=true)
    public class AppConfig {
        //...
    }
        @PropertySources({
        @PropertySource(value = "classpath:missing.properties", ignoreResourceNotFound=true),
        @PropertySource("classpath:config.properties")
        })

完了しました。