This example shows how Resource instance can be injected directly with @Value annotation.
Resource
public class MyBean { @Value("classpath:myResource.txt") private Resource myResource; ... }
this is a test resource.
package com.logicbig.example; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import java.io.File; import java.io.IOException; import java.nio.file.Files; @Configuration public class InjectResourceExample { @Bean public ClientBean clientBean () { return new ClientBean(); } public static void main (String[] args) throws IOException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( InjectResourceExample.class); ClientBean bean = context.getBean(ClientBean.class); bean.doSomething(); } private static class ClientBean { @Value("classpath:myResource.txt") private Resource myResource; public void doSomething () throws IOException { File file = myResource.getFile(); String s = new String(Files.readAllBytes(file.toPath())); System.out.println(s); } } }
package com.logicbig.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import java.io.File; import java.io.IOException; import java.nio.file.Files; @Configuration public class InjectResourceDataExample { @Bean public ClientBean clientBean() { return new ClientBean(); } @Bean public String myResourceData( @Value("classpath:myResource.txt") Resource myResource) throws IOException { File file = myResource.getFile(); return new String(Files.readAllBytes(file.toPath())); } public static void main(String[] args){ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( InjectResourceDataExample.class); ClientBean bean = context.getBean(ClientBean.class); bean.doSomething(); } private static class ClientBean { @Autowired private String myData; public void doSomething() { System.out.println(myData); } } }
Example project below has examples of file and url resource loading as well.
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.