2014-01-21 49 views
4

我想通過.proprerties文件配置我的bean String字段。但它不會替換值鍵,意味着它會回顯「$ {value}」字符串。我下面的代碼:無法使用註釋從.properties文件中提取值

主類:

public class Main { 

    public static void main(String[] args) { 
     ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml"); 
     ValuesContainer valuesContainer = (ValuesContainer) applicationContext.getBean("container"); 
     System.out.println(valuesContainer.getValue()); //echoes "${value}" instead of Ho-ho-ho! 
    } 
} 

應用程序上下文:

..... 
<context:annotation-config /> 
<context:component-scan base-package="bean"/> 

豆:

package bean; 

import org.springframework.beans.factory.annotation.Value; 
import org.springframework.context.annotation.PropertySource; 
import org.springframework.context.annotation.Scope; 
import org.springframework.stereotype.Component; 

@Component("container") 
@Scope("singleton") 
@PropertySource(value = "classpath:app.properties") 
public class ValuesContainer { 

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

    public String getValue() { 
     return value; 
    } 
} 

個app.properties:

value = Ho-ho-ho! 

回答

2

它看起來像你缺少你配置的PropertySourcesPlaceholderConfigurer。

參見this post

+0

你是對的,謝謝 –

2

@PropertySource應與@Configuration一起使用。

您需要創建一個單獨的@Configuration類,將其註釋@PropertySource添加到您的應用程序上下文(或讓<context:component-scan>添加它)。

或者,您可以通過編程方式配置應用程序上下文的屬性來源using Environment

相關問題