2022-06-07:使用Resource

在Java程序中,我们经常会读取配置文件、资源文件等。使用Spring容器时,我们也可以把“文件”注入进来,方便程序读取。

例如,AppService需要读取logo.txt这个文件,通常情况下,我们要写很多繁琐的代码,主要是为了定位文件,打开InputStream

Spring提供了一个org.springframework.core.io.Resource(不是javax.annotation.Resource),它可以像String、int一样使用@Value注入:

@Component
public class AppService {
    @Value("classpath:/logo.txt")
    private Resource resource;

    private String logo;

    @PostConstruct
    public void init() throws IOException {
        try (var reader = new BufferedReader(
                new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
            this.logo = reader.lines().collect(Collectors.joining("\n"));
        }
    }
}

注入Resource最常用的方法是通过classpath,即类似classpath:/logo.txt表示在classpath中搜索logo.txt文件,然后我们直接调用Resource.getInputStream()就可以获取到输出流,避免了自己搜索文件的代码。

也可以直接指定文件的路径,例如:

@Value("file:/path/to/logo.txt")
private Resource resource;

但使用classpath是最简单的方式。上述工程结构如下:

 

使用Maven的标准目录结构,所有的资源文件放入src/main/resource即可。

小结

  • Spring提供了Resource类便于注入资源文件;
  • 最常用的注入是通过classpath以classpath:/path/to/file的形式注入。

 

posted @ 2022-06-07 14:48  ShineLe  阅读(53)  评论(0)    收藏  举报