2013-04-04 104 views
2

我有一個類FichierCommunRetriever,它使用Spring@Value註釋。但我正在努力使其工作。@Value註釋不返回值

所以在我的application.properties我:

application.donneeCommuneDossier=C\:\\test 
application.destinationDonneeCommuneDossier=C\:\\dev\\repertoireDonneeCommune\\Cobol 

我班FichierCommunRetriever使用這些條目下面的代碼:

public class FichierCommunRetriever implements Runnable { 

    @Value("${application.donneeCommuneDossier}") 
    private String fichierCommunDossierPath; 

    @Value("${application.destinationDonneeCommuneDossier}") 
    private String destinationFichierCommunDossierPath; 
} 

我們正在加載application.properties與類ApplicationConfig下面的代碼:

@ImportResource("classpath:/com/folder/folder/folder/folder/folder/applicationContext.xml") 

ApplicationConfig,我定義一個bean,在一個新的線程像使用FichierCommunRetriever

Thread threadToExecuteTask = new Thread(new FichierCommunRetriever()); 
threadToExecuteTask.start(); 

我想我的問題是,因爲FichierCommunRetriever在一個單獨的線程運行,類不能達到applicationContext並且無法給出價值。

我想知道如果註釋會起作用,或者我必須改變我得到這些值的方式?

回答

2

在你applicationConfig你應該定義你的bean是這樣的:

@Configuration 
public class AppConfig { 

    @Bean 
    public FichierCommunRetriever fichierCommunRetriever() { 
     return new FichierCommunRetriever(); 
    } 

} 

然後,春加載後,您可以通過應用程序上下文訪問你的bean

FichierCommunRetriever f = applicationContext.getBean(FichierCommunRetriever.class); 
Thread threadToExecuteTask = new Thread(f); 
threadToExecuteTask.start(); 

現在你確信你的bean存在於Spring上下文中並且它已被初始化。 此外,在Spring XML,你必須加載的屬性(本例中使用上下文命名空間):

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation=" 
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd"> 

... 

<context:property-placeholder location="classpath:application.properties" /> 

... 

</beans> 
+0

非常感謝它的工作完美。 – 2013-04-04 18:43:41

2

您使用new,而不是問春返回一個bean實例創建FichierCommunRetriever的一個實例。所以Spring並不控制這個實例的創建和注入。

你應該在你的配置類下面的方法,並調用它來獲取bean實例:

@Bean 
public FichierCommunRetriever fichierCommunRetriever() { 
    return new FichierCommunRetriever(); 
} 

... 
    Thread threadToExecuteTask = new Thread(fichierCommunRetriever()); 
+0

良好的信息非常感謝 – 2013-04-04 18:44:14