java - @Value注释不返回值

标签 java spring spring-annotations

我有一个类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/

相关文章:

java - 使线程跳过从其他线程读取输入操作

java - java中void方法的正确单元测试,无需模拟

java - 在 JPA 存储库中使用 @MOdify 和 @Query 受哪些规则约束?

java - 将 <bean/> 代码转换为 @Bean

spring - 无法解析未找到 WebApplicationContext : no ContextLoaderListener registered

java - WindowIconfield 和 FocusLost 不能一起使用

java - 错误或长请求

java - 如何将Angular(7)添加到可部署的 war 中

来自配置的 Spring 注释值

java - ArrayList 和 Array 在 JSON 中的表示方式是否不同?