将类路径资源注入 Spring 3 bean

发布于 2024-11-29 03:20:38 字数 754 浏览 0 评论 0原文

有一个类型为 Resource 应该通过对类路径中文件的引用来注入。我使用下面的 @Value 注释来希望实现这一点。

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

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

我可以谷歌搜索到的最接近的解决方案是 thisthis 详细介绍了 xml 方式,而我有兴趣使用注释来执行此操作。

感谢任何有关此处可能出现问题的指示。

谢谢,

维杰

There is a property of type Resource in my Spring 3 bean that should be injected with a reference to a file in the classpath. I use the @Value annotation as below to hopefully achieve this.

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

But the property is always null. I have confirmed that the sql file has been deployed in the maven target directory (it is at target/classes/abc/student/test.sql).

The closest solutions that I could google were this and this which detail the xml way whereas I am interested in doing this using annotations.

Appreciate any pointers on what could be wrong here.

Thanks,

Vijay

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

命硬 2024-12-06 03:20:38

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

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

否则,您真正想要的是

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

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

If it's going to be hard-coded like that, then just

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

Otherwise, what you're really after is

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

and I believe that in injecting the property value, the correct PropertyEditor will be applied.

不气馁 2024-12-06 03:20:38

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

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

If you don't want to specify a property then this should work

@Value("${:classpath:json/inventory.json}")
Resource inventory;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文