spring可以从配置为的资源中以文本形式加载整个文件

bsxbgnwa  于 2021-07-15  发布在  Java
关注(0)|答案(1)|浏览(265)

可以将整个资源文件作为干净的文本加载,并用干净的java编写spring引导配置。
这就是我到现在为止的成就:
应用程序.yml

some-common-config:
   my-text-file: classpath:/<DIRECTORY>/<FILENAME>

配置类:

@ConfigurationProperties(prefix = "some-common-config")
public class SomeCommonConfig {
    private String myTextFile;
}

文件内容(src/resources/test of file/file.txt):

THIS IS JUST A EXAMPLE

那我想

assert SomeCommonConfig -> myTextFile == "THIS IS JUST A EXAMPLE"
eit6fx6z

eit6fx6z1#

你可以把它当作 InputStream 然后将 InputStream 无论你喜欢什么:
例如对一个 String :

@ConfigurationProperties(prefix = "some-common-config")
public class SomeCommonConfig {

    private InputStream myTextFile;

    public String getText() {
        return new BufferedReader(
                new InputStreamReader(myTextFile, StandardCharsets.UTF_8))
                .lines()
                .collect(Collectors.joining("\n"));
    }

    public InputStream getMyTextFile() {
        return myTextFile;
    }

    public void setMyTextFile(InputStream myTextFile) {
        this.myTextFile = myTextFile;
    }
}

相关问题