2014-12-11 35 views
19

.yml文件@ConfigurationProperties沒有前綴的工作

cassandra: 
    keyspaceApp:junit 
solr: 
    keyspaceApp:xyz 

@Component 
@ConfigurationProperties(prefix="cassandra") 
public class CassandraClientNew { 
    @Value("${keyspaceApp:@null}") private String keyspaceApp; 

主要方法文件

@EnableAutoConfiguration 
@ComponentScan 
@PropertySource("application.yml") 
public class CommonDataApplication { 
    public static void main(String[] args) { 
     ConfigurableApplicationContext context = new SpringApplicationBuilder(CommonDataApplication.class) 
       .web(false).headless(true).main(CommonDataApplication.class).run(args); 
    } 
} 

的TestCase

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration(classes = CommonDataApplication.class) 
@IntegrationTest 
@EnableConfigurationProperties 
public class CassandraClientTest { 

    @Autowired 
    CassandraClientNew cassandraClientNew; 

    @Test 
    public void test(){ 
     cassandraClientNew.getSession(); 
     System.out.println(" **** done ****"); 
    } 
} 

它不是將junit設置爲keyspaceApp,而是設置xyz。

貌似PREFIX =「卡桑德拉」不工作

+0

您正在使用什麼春/啓動的版本? – 2014-12-12 07:26:07

回答

34

看起來你正在嘗試使用Spring Boot Typesafe Configuration Properties功能。

所以爲了讓它正常工作,你必須添加到您的代碼的一些變化:

首先,你CommonDataApplication類應該有@EnableConfigurationProperties註釋例如

@EnableAutoConfiguration 
@ComponentScan 
@PropertySource("application.yml") 
@EnableConfigurationProperties 
public class CommonDataApplication { 
    public static void main(String[] args) { 
     // ... 
    } 
} 

我不相信你需要@PropertySource("application.yml")標註爲application.yml(以及application.propertiesapplication.xml)是由Spring啓動時使用一個默認的配置文件。

您的CassandraClientNew類不需要有@Value註釋前綴keyspaceApp屬性。而你的keyspaceApp必須有一個setter方法

@Component 
@ConfigurationProperties(prefix="cassandra") 
public class CassandraClientNew { 
    private String keyspaceApp; 

    public String setKeyspaceApp(String keyspaceApp) { 
     this.keyspaceApp = keyspaceApp; 
    } 
} 

順便說一句,如果要使用List的或Set秒和你初始化集合(例如List<String> values = new ArrayList<>();),則僅吸氣劑是必需的。如果一個集合沒有被初始化,那麼你也需要提供一個setter方法(否則會拋出異常)。

我希望這會有所幫助。

+0

Thx,它真的幫了大忙!我的問題確實是缺席的二傳手!但我有點困惑:春天教會我們不要對所有訪問器和修飾符都不屑一顧,突然之間它不能注入財產而沒有二傳手......這不是很奇怪嗎? – vk23 2017-06-22 19:52:37

1

我不知道在哪裏的「XYZ」是從哪裏來的(也許你沒有顯示你的整個application.yml?)。儘管(你無法知道你的前綴是什麼),你通常不會與@Value@ConfigurationProperties中綁定。你真的在任何地方都有@EnableCongigurationProperties嗎?您是否使用SpringApplication來創建應用程序上下文?

+0

添加了更多信息。讓我知道如果這有幫助與否。 – plzdontkillme 2014-12-11 08:09:44

+0

希望看到@value可以將默認值分配給屬性 – plzdontkillme 2014-12-11 08:44:03

+1

您可以自己分配默認值,如果屬性匹配,則該值將被覆蓋。 – 2014-12-11 09:09:26