简体   繁体   中英

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. 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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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