Spring是否有一个注释来将类路径内容读取到String?

问题描述 投票:4回答:2

我想将类路径中的文件内容(在resources/中)读取到String。 Spring有一个方便的注释吗?

就像是:

public class MyClass {
    @Resource("classpath:data.txt")
    private String data;
}

春天有类似的东西吗?

java spring io
2个回答
2
投票
@Value("classpath:data.txt")
private Resource data;

你不能注入String,但你可以使用一个名为Resource的Spring抽象来获取文件并自己阅读它的内容。

我认为Spring将责任归咎于你,否则它会非常脆弱;在访问/读取资源期间可能会发生不同的IO事情,导致IOException

此外,文件到字符串的转换并不常见,以使Spring实现它。


1
投票

@Value annotation用于将属性值注入变量,通常是字符串或简单的原始值。你可以找到更多信息here

如果要加载资源文件,请使用ResourceLoader,如:

@SpringBootApplication
public class ExampleApplication implements CommandLineRunner {

    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    private CountWords countWords;

    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Count words : " + countWords.getWordsCount(resourceLoader.getResource("classpath:file.txt")));

    }
}

另一种解决方案,你可以像@Value一样使用:

@SpringBootApplication
public class ExampleApplication implements CommandLineRunner {


    @Value("classpath:file.txt")
    private Resource res;

    @Autowired
    private CountWords countWords;

    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Count words : " + countWords.getWordsCount(res));

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.