2013-04-04 92 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