【问题标题】:Injecting a classpath resource into a Spring 3 bean将类路径资源注入 Spring 3 bean
【发布时间】:2019-08-22 07:22:38
【问题描述】:

在我的 Spring 3 bean 中有一个 Resource 类型的属性,它应该被注入到类路径中的文件的引用中。我使用下面的@Value 注释来希望实现这一点。

public class TestBean
{
    @Value("classpath:/abc/student/test.sql")
    private Resource SqlFile;
    ...
}

但该属性始终为空。我已经确认 sql 文件已经部署在 maven 目标目录中(它位于 target/classes/abc/student/test.sql)。

我可以用谷歌搜索的最接近的解决方案是thisthis,它们详细说明了 xml 方式,而我有兴趣使用注释来做到这一点。

感谢任何关于此处可能出错的指针。

谢谢,

维杰

【问题讨论】:

    标签: java spring dependency-injection


    【解决方案1】:

    如果要像这样硬编码,那么就

    private Resource sqlFile = new ClassPathResource("/abc/student/test.sql");
    

    否则,你真正追求的是

    @Value("${some.property}")
    private Resource sqlFile;
    

    而且我相信在注入属性值时,将应用正确的 PropertyEditor。

    【讨论】:

    • 感谢您的回复。两种解决方案都有效。我更喜欢 @Value 方法,因为它不允许我的代码依赖于 Spring 类。
    • 你知道@Value 是一个弹簧类吗?
    【解决方案2】:

    如果您不想指定属性,那么这应该可以工作

    @Value("${:classpath:json/inventory.json}")
    Resource inventory;
    

    【讨论】:

      猜你喜欢
      • 2013-04-05
      • 2015-08-07
      • 1970-01-01
      • 2011-03-30
      • 2014-06-27
      • 1970-01-01
      • 2010-12-08
      • 2011-12-15
      • 2015-11-09
      相关资源
      最近更新 更多