2016-07-09 12 views
8

私には春の起動アプリケーションがあり、私はapplication.propertiesファイルからいくつかの変数を読みたいと思っています。上記のコードがそうです。しかし、私はこの代替案のための良い方法があると思います。Springブートを使用してJavaプロパティファイルからデータを読み取る方法

Properties prop = new Properties(); 
InputStream input = null; 

try { 
    input = new FileInputStream("config.properties"); 
    prop.load(input); 
    gMapReportUrl = prop.getProperty("gMapReportUrl"); 
} catch (IOException ex) { 
    ex.printStackTrace(); 
} finally { 
    ... 
} 

答えて

19

@PropertySourceを使用すると、構成をプロパティファイルに外部化できます。プロパティを取得行う方法はいくつかあります:

1. は@Value${}を解決するためにPropertySourcesPlaceholderConfigurer@Valueを使用してフィールドにプロパティ値を割り当てます。

@Configuration 
@PropertySource("file:config.properties") 
public class ApplicationConfiguration { 

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

    @Bean 
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() { 
     return new PropertySourcesPlaceholderConfigurer(); 
    } 

} 

2. プロパティを取得します。 Environmentを使用して値:

希望するこれは助けることができます

+0

なぜfooは無効ですか?このクラスの使い方は? – gstackoverflow

-1

クラスパス上のプロパティファイルを読み込む標準的な方法であるリソースバンドルを使用することをお勧めします(特定のファイルでも使用できます)。

リソースバンドルは、通常、キー値のペアを格納するファイルで使用されます。

コードサンプル:

ResourceBundle bundle = ResourceBundle.getBundle("config"); //creates bundle from file `config.properties` 
List<String> keys = (List<String>) bundle.getKeys(); //gets the list of keys found in the bundle (file) 
String value = bundle.getString("gMapReportUrl"); //gets the value for the key `mykey` 

config.properties:あなたはできるはずですこれらの方法の組み合わせを使用して

gMapReportUrl = someValueの

someOtherKey =ランダム

あなたが必要とするすべてのデータをプロから入手するpertyファイル。ここにあなたの新しいプロパティは、名前が「otherprops.properties」で、プロパティ名が「がmyName」であるファイル

@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties") 
@Controller 
public class ClassA { 
    @Value("${myName}") 
    String name; 

    @RequestMapping(value = "/xyz") 
    @ResponseBody 
    public void getName(){ 
     System.out.println(name); 
    } 
} 

+0

Springアプリケーションのプロパティファイルにアクセスする適切な方法ではありません。 –

+0

春のブートはより良い実装を持っています... – SAM

3

iは、以下の方法をお勧めします。これは、Springブートバージョン1.5.8のプロパティファイルにアクセスするための最も簡単な実装です。

関連する問題