简体   繁体   English

将类路径资源注入Spring 3 bean

[英]Injecting a classpath resource into a Spring 3 bean

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. 我的Spring 3 bean中有一个Resource类型的属性,应该在类路径中引用一个文件。 I use the @Value annotation as below to hopefully achieve this. 我使用如下的@Value注释来希望实现这一点。

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

But the property is always null. 但该属性始终为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). 我已经确认sql文件已部署在maven目标目录中(它位于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. 我可以google最接近的解决方案是这个详细说明了xml的方式,而我有兴趣使用注释来做这个。

Appreciate any pointers on what could be wrong here. 感谢关于这里可能出错的任何指示。

Thanks, 谢谢,

Vijay 维杰

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. 我相信在注入属性值时,将应用正确的PropertyEditor。

If you don't want to specify a property then this should work 如果您不想指定属性,那么这应该有效

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM