Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 710
Babu Subburathinam Avatar asked Aug 11 '11 00:08

Babu Subburathinam


People also ask

How do I load resources from classpath?

We can either load the file(present in resources folder) as inputstream or URL format and then perform operations on them. So basically two methods named: getResource() and getResourceAsStream() are used to load the resources from the classpath. These methods generally return the URL's and input streams respectively.

What is classpath resource in Spring?

ClassPathResource is a Resource implementation for class path resources. It supports resolution as java. io. File if the class path resource resides in the file system, but not for resources in a JAR.

How do you inject specific beans in a Spring boot?

In Spring Boot, we can use Spring Framework to define our beans and their dependency injection. The @ComponentScan annotation is used to find beans and the corresponding injected with @Autowired annotation. If you followed the Spring Boot typical layout, no need to specify any arguments for @ComponentScan annotation.


1 Answers

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.

like image 65
Ryan Stewart Avatar answered Oct 11 '22 16:10

Ryan Stewart