[JAVA] A review note of the Spring Framework Resource interface

Overview

This is a memo when I reviewed how to access resource files using the Resource interface and implementation class of Spring Framework.

environment

reference

Resource

Since 28.12.2003

Interface for a resource descriptor that abstracts from the actual type of underlying resource, such as a file or class path resource.

How to get an instance of Resource interface

  1. Use the implementation class
  2. Use ResourceLoader
  3. Use the @Value annotation

And so on.

How to use implementation class

How to use the appropriate Resource interface implementation class depending on the location of the resource file. For example, there are ClassPathResource to access resources in the classpath, ʻUrlResource to access resources on the network, and FileUrlResource` to access resources on the file system.

ClassPathResource

Since 28.12.2003

Resource implementation for class path resources. Uses either a given ClassLoader or a given Class for loading resources.

constructor
ClassPathResource(String path)
ClassPathResource(String path, Class<?> clazz)
ClassPathResource(String path, ClassLoader classLoader)

code

Resource resource = new ClassPathResource("config/app.properties");

Since the Resource interface inherits the ʻInputStreamSource interface, you can get the ʻInputStream of the resource file with the getInputStream method.

String read(Resource resource) {
    try (InputStream in = resource.getInputStream();
         BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

Since the Resource interface also has a getFile method, it can be described as follows, but since an exception is thrown when the resource is in the classpath or on the network, the resource file is usually on the file system. I think you should use it only in certain cases.

String read(Resource resource) {
    try {
        return Files.readString(resource.getFile().toPath());
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

UrlResource

Since 28.12.2003

Resource implementation for java.net.URL locators. Supports resolution as a URL and also as a File in case of the "file:" protocol.

constructor
UrlResource(String path)
UrlResource(String protocol, String location)
UrlResource(String protocol, String location, String fragment)
UrlResource(java.net.URI uri)
UrlResource(java.net.URL url)

code

Resource urlResource = new UrlResource("http://localhost:8887/config/app.properties");

FileUrlResource

Since 5.0.2

Subclass of UrlResource which assumes file resolution, to the degree of implementing the WritableResource interface for it. This resource variant also caches resolved File handles from getFile().

constructor
FileUrlResource(String location)
FileUrlResource(java.net.URL url)

code

Resource fileUrlResource = new FileUrlResource("c://var//config/app.properties");

How to use ResourceLoader

Since 10.03.2004

Strategy interface for loading resources (e.. class path or file system resources). An ApplicationContext is required to provide this functionality, plus extended ResourcePatternResolver support. DefaultResourceLoader is a standalone implementation that is usable outside an ApplicationContext, also used by ResourceEditor.

ResourceLoader Instance of Resource using implementation class of interface If you get, there is an advantage that you do not need to be aware of the implementation class of the Resource interface.

In Spring Boot, ResourceLoader is injected with an instance of the ʻAnnotationConfigServletWebServerApplicationContext` class. (This class is in the Spring Boot project)

@Autowired
private ResourceLoader resourceLoader;
// org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext

classpath

Writing starting with classpath: will inject an instance of the ClassPathResource class.

Resource resource = resourceLoader.getResource("classpath:config/app.properties");
// org.springframework.core.io.ClassPathResource

url

When written in the http scheme, an instance of the ʻUrlResource` class is injected.

Resource resource = resourceLoader.getResource("http://localhost:8887/config/app.properties");
// org.springframework.core.io.UrlResource

file

An instance of the FileUrlResource class will be injected as described in the file scheme.

Resource resource = resourceLoader.getResource("file:///c://config/app.properties");
// org.springframework.core.io.FileUrlResource

How to use the @Value annotation

Depending on the value of the Value annotation, the Spring Framework will inject an instance of the appropriate implementation class. The format of the value described in the annotation is the same as ResourceLoader.

classpath

@Value("classpath:config/app.properties")
private Resource classpathResource;
// org.springframework.core.io.ClassPathResource

url

@Value("http://localhost:8887/config/app.properties")
private Resource urlResource;
// org.springframework.core.io.UrlResource

file

@Value("file:///c://config/app.properties")
private Resource fileUrlResource;
// org.springframework.core.io.FileUrlResource

How to use ResourceUtils

Since 1.1.5

Utility methods for resolving resource locations to files in the file system. Mainly for internal use within the framework.

As described in the API documentation, it is a utility class mainly for use inside the Spring Framework. There is no statement that it should not be used on the application side, but it should be used with caution as it is intended for use within the framework.

classpath

File file = ResourceUtils.getFile("classpath:config/app.properties");

url

URL url = ResourceUtils.getURL("http://localhost:8887/config/app.properties");

file

File file = ResourceUtils.getFile("file:///c://var//config/app.properties");

StreamUtils

Since 3.2.2

Simple utility methods for dealing with streams. The copy methods of this class are similar to those defined in FileCopyUtils except that all affected streams are left open when done. All copy methods use a block size of 4096 bytes. Mainly for use within the framework, but also useful for application code.

The Spring Framework also has utility classes that handle streams. You can use the copyToString method of this class to simplify your code as follows:

String data = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);

Recommended Posts

A review note of the Spring Framework Resource interface
A record of studying the Spring Framework from scratch
A review note for the class java.util.Scanner
About the initial display of Spring Framework
A review note for the class java.util.Optional
A review note for the class java.util.Objects
A review note for the package java.time.temporal
About the official start guide of Spring Framework
A review of the code used by rails beginners
A survey of the Kubernetes native Java framework Quarkus
A note about the scope
A story packed with the basics of Spring Boot (solved)
A note about the seed function of Ruby on Rails
I tried JAX-RS and made a note of the procedure
Spring Framework 5.0 Summary of major changes
Get a proxy instance of the component itself in Spring Boot
Note on the path of request.getRequestDispatcher
A memorandum of the FizzBuzz problem
Filter the result of BindingResult [Spring]
We will build a Spring Framework development environment in the on-premises environment.
(Note) Get a set of dependent library jars with the help of Gradle
The story of encountering Spring custom annotation
Make a note of Ruby keyword arguments
A note on the libGDX Utils class
Why spring consider as a lightweight framework
Features of spring framework for java developers
A rudimentary note on the Fibonacci sequence
Find the difference from a multiple of 10
[Java] [Spring] Test the behavior of the logger
Check the operation of the interface through threads
Introducing the Spring Boot Actuator, a function that makes the operation of Spring Boot applications easier.
A quick note on using jshell with the official Docker image of the JDK
I want to recursively get the superclass and interface of a certain class
Make a margin to the left of the TextField
Measure the size of a folder in Java
Set the time of LocalDateTime to a specific time
A note when the heroku command becomes unavailable
The story of raising Spring Boot 1.5 series to 2.1 series
Let's check the feel of Spring Boot + Swagger 2.0
Transaction management of the integrated framework "Apache Camel"
Matches annotations on the interface with Spring AOP
A note about the Rails and Vue process
The official name of Spring MVC is Spring Web MVC
A description of Interface that is often mistaken
Let's experience the authorization code grant flow with Spring Security OAuth-Part 1: Review of OAuth 2.0