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
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.
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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With