2014-03-27 78 views
0

我小的測試項目,測試Spring註解:Spring註解,讀取屬性

enter image description here

其中nejake.properties是:

klucik = hodnoticka 

App.java是:

@Configuration 
@PropertySource("classpath:/com/ektyn/springProperties/nejake.properties") 
public class App 
{ 
    @Value("${klucik}") 
    private String klc; 



    public static void main(String[] args) 
    { 
     AnnotationConfigApplicationContext ctx1 = new AnnotationConfigApplicationContext(); 
     ctx1.register(App.class); 
     ctx1.refresh(); 
     // 
     App app = new App(); 
     app.printIt(); 
    } 



    private void printIt() 
    { 
     System.out.println(klc); 
    } 
} 

它應該打印hodnoticka在控制檯上,但打印null - 字符串值未初始化。我的代碼很糟糕 - 目前我沒有使用註釋驅動的Spring的經驗。上面的代碼有什麼不好?

回答

2

您創建的對象自己

App app = new App(); 
app.printIt(); 

春季應該如何管理實例,並注入價值?

您將需要但是

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

使可用屬性。另外,因爲初始化處理@ConfigurationApp bean已在解析器@Value之前初始化,所以值字段將不會被設置。相反,聲明不同的App豆和檢索

@Bean 
public App appBean() { 
    return new App(); 
} 
... 
App app = (App) ctx1.getBean("appBean"); 
0

你需要從一個Spring bean訪問屬性,你需要正確線的性質。首先,添加到您的配置類中:

@Bean 
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() { 

    PropertySourcesPlaceholderConfigurer props = new PropertySourcesPlaceholderConfigurer(); 
    props.setLocations(new Resource[] { new ClassPathResource("com/ektyn/springProperties/nejake.properties") }); //I think that's its absolute location, but you may need to play around with it to make sure 
    return props; 
} 

然後,您需要從Spring Bean中訪問它們。通常情況下,你的配置文件不應該是一個bean,所以我會建議你做一個單獨的類,像這樣:

@Component //this makes it a spring bean 
public class PropertiesAccessor { 

    @Value("${klucik}") 
    private String klc; 

    public void printIt() { 
     System.out.println(klc); 
    } 
} 

最後,它添加到你的配置,使其找到PropertiesAccessor

@ComponentScan("com.ektyn.springProperties")

然後,您可以從您的應用上下文訪問PropertiesAccessor bean並調用其printIt方法。