我有一个类FichierCommunRetriever
,它使用Spring
的@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;
}
我们正在 ApplicationConfig
类中使用以下代码加载 application.properties
:
@ImportResource("classpath:/com/folder/folder/folder/folder/folder/applicationContext.xml")
在 ApplicationConfig
中,我定义了一个 bean
,它在新线程中使用 FichierCommunRetriever
:
Thread threadToExecuteTask = new Thread(new FichierCommunRetriever());
threadToExecuteTask.start();
我想我的问题是,由于 FichierCommunRetriever 在单独的线程中运行,该类无法访问 applicationContext 并且无法给出值。
我想知道注释是否有效,或者我必须更改获取这些值的方式?
最佳答案
在你的 applicationConfig 中,你应该这样定义你的 bean:
@Configuration
public class AppConfig {
@Bean
public FichierCommunRetriever fichierCommunRetriever() {
return new FichierCommunRetriever();
}
}
然后,在 Spring 加载后,您可以通过应用程序上下文访问您的 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>
关于java - @Value注释不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15818839/