Spring @Value - プロパティファイルからリストをインポートする

Spring @Value –プロパティファイルからリストをインポートする

このチュートリアルでは、Spring EL@Valueを介してプロパティファイルから「リスト」をインポートする方法を示します。

テスト済み:

  1. 春4.0.6

  2. JDK 1.7

Spring @Valueとリスト

Spring@Valueでは、split()メソッドを使用して、「リスト」を1行に挿入できます。

config.properties

server.name=hydra,zeus
server.id=100,102,103

AppConfigTest.java

package com.example.analyzer.test;

import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@PropertySource(value="classpath:config.properties")
public class AppConfigTest {

    @Value("#{'${server.name}'.split(',')}")
    private List servers;

    @Value("#{'${server.id}'.split(',')}")
    private List serverId;

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

}

出力

    System.out.println(servers.size());
    for(String temp : servers){
        System.out.println(temp);
    }

    System.out.println(serverId.size());
    for(Integer temp : serverId){
        System.out.println(temp);
    }
2
hydra
zeus

3
100
102
103