2017-09-05 89 views
0

通過@ConfigrationProperties編寫彈簧配置時,有一種方法可以連接配置的根值。Spring @ConfigurationProperties根配置

我的配置是一樣的東西

foo.bar=hello 
foo.bar.baz=world 

我怎樣才能獲得價值了foo.bar變量。目前我有這個

@Configuration 
@ConfigurationProperties("foo.bar") 
public class FooBar { 
    private String baz; 

    // Getters and setters... 
} 

我不能改變模式。屬性來自env變量FOO_BARFOO_BAR_BAZ

+1

只需使用'@ Value'綁定屬性,這在這種情況下可能是最簡單的。 –

回答

0

@PropertySource註釋標註您的班級並添加一個變量以獲取它。

@PropertySource("classpath:config.properties") 
public class FooBar { 
    @Value("${foo.bar}") 
     private String baz; 
} 
+0

這不適用於環境變量。 –

1

您需要使用@EnableConfigurationProprties(FooBar.class)來告訴spring boot爲您的配置創建一個bean。像這樣的東西應該適合你:

@Configuration 
@EnableConfigurationProperties(FooBar.class) 
class MyConfiguration { 
    final FooBar fooBar; 

    MyConfiguration(FooBar fooBar) { 
     this.fooBar = fooBar; 
    } 

    @ConfigurationProperties("foo.bar") 
    static class FooBar { 
     String baz; 
     // .... 
    } 

    @Bean 
    MyBean myBean() { 
     // use this.fooBar here... 
    } 
}