2014-08-29 86 views
0

按照這些說明here我想讓我的MQConnection類屬性從application.properties文件中加載。spring-boot外部配置整個類

問題是,只有當我在每個屬性上放置@Value(「$ {attributename}」)註釋時,纔會加載屬性。我不想標記每個屬性,而是設置類前綴,並讓Spring關聯並將我的類屬性映射到application.properties中的屬性。

我的設置:

  • application.properties是對的src/main /資源類路徑
  • 我@Configuration類也有@EnableConfigurationProperties
  • 我MQConnection類既有@ Component和@ConfigurationProperties(prefix =「mq」)

Configuration類:

@Configuration 
@EnableAutoConfiguration 
@EnableConfigurationProperties 
@ComponentScan 
public class Application implements CommandLineRunner { 
... 
} 

MQConnection類:

@Component 
@ConfigurationProperties(prefix="mq") 
public class MQConnection{ 

    @Value("${mq.hostname}") // will only work if @Value is here, don't want this 
    private String hostname; 
    private int port; 
    private String qmanager; 
    private String queue; 
    private String channel; 
} 

application.properties:

mq.hostname=localhost 
mq.port=5120 
mq.qmanager=MyQueueManager 
mq.queue=MyQueue 
mq.channel=MyChannel 

回答

2

您的MQConnection類不是Java bean(沒有getters和setters),所以Spring無法綁定到它。如果您不喜歡getter和setter,請使用Groovy或Project Lombok

+0

啊!就是這樣。我不介意getter/setters,但我很好奇爲什麼它需要在那裏。 Spring能夠在沒有getter/setter的情況下向私有成員注入值,這是不可能的(或者不希望的)配置屬性?謝謝! – szxnyc 2014-08-31 19:46:10

+0

如果框架('BeanWrapper')和AFAIK只有一個全局設置,字段或屬性到處都適合每個人,這是最古老的部分之一。所以我認爲如果不打破宇宙中所有其他bean的話,你就無法爲bean設置字段。我想錯了。但是,無論如何,Project Lombok使得這一切都相當學術,因爲你的類可以擁有沒有源代碼需要它們的屬性。 – 2014-08-31 21:02:15

0

此問題的根本原因可能是由於是錯過了通過@Configuration在配置文件中註釋@EnableConfigurationProperties註釋。

+0

感謝您的評論,因爲您可以看到我設置了@EnableConfigurationProperties,因此這不是我的問題。事實證明,正如Dave Syer所說的那樣,缺乏getter/setter。 – szxnyc 2014-08-31 19:43:49