66

如何加载 Spring 资源内容并使用它来设置 bean 属性或将其作为参数构造函数传递?

该资源包含自由文本。

4

7 回答 7

55

在一行中尝试阅读 test.xml:

String msg = StreamUtils.copyToString( new ClassPathResource("test.xml").getInputStream(), Charset.defaultCharset()  );
于 2017-12-01T10:51:38.083 回答
32
<bean id="contents" class="org.apache.commons.io.IOUtils" factory-method="toString">
    <constructor-arg value="classpath:path/to/resource.txt" type="java.io.InputStream" />
</bean>

此解决方案需要 Apache Commons IO。

@Parvez 建议的另一个解决方案,没有 Apache Commons IO 依赖项是

<bean id="contents" class="java.lang.String">
    <constructor-arg>
        <bean class="org.springframework.util.FileCopyUtils" factory-method="copyToByteArray">
            <constructor-arg value="classpath:path/to/resource.txt" type="java.io.InputStream" />
        </bean>     
    </constructor-arg>
</bean>
于 2012-12-24T14:58:37.177 回答
13

只需阅读它:

    try {
        Resource resource = new ClassPathResource(fileLocationInClasspath);
        BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()),1024);
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            stringBuilder.append(line).append('\n');
        }
        br.close();
        return stringBuilder.toString();
    } catch (Exception e) {
        LOGGER.error(e);
    }
于 2012-12-25T09:40:12.667 回答
4

这是一种不使用任何外部库的方法。spring 提供的默认值。environment.properties 文件包含键值对...使用 ${key} 引用每个值

在我的示例中,我保留了数据库道具

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list value-type="org.springframework.core.io.Resource">
            <value>classpath:environment.properties</value>

        </list>
    </property>
</bean>
<bean id="mySQLdataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${JDBC.driver}" />
    <property name="url" value="${JDBC.URL}" />
    <property name="username" value="${JDBC.username}" />
    <property name="password" value="${JDBC.password}" />
</bean>
于 2012-12-24T15:09:55.553 回答
2

2021 年更新。

您可以使用 Spring 的Resource接口来获取文本文件的内容,然后使用StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset());来获取文本。

一个例子如下:

    @Value("classpath:appVersionFilePath")
    private Resource resource;

    @GetMapping(value = "/hello")
    public HttpResult<String> hello() throws IOException {
        String appVersion = StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset());
        // ...
    }
于 2021-12-06T12:30:31.820 回答
1

daoway 的回答非常有帮助,按照Adrian的评论,我正在添加一个类似于 daoway 的代码的配置片段

<bean id="contents" class="org.springframework.core.io.ClassPathResource">
    <constructor-arg value="path/to/resource.txt"/>
</bean>

从你的组件

    @Autowired
    private Resource contents;

    @PostConstruct
    public void load(){
        try {
            final InputStream inputStream = contents.getInputStream();
                //use the stream 
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream ,1024);
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                stringBuilder.append(line).append('\n');
            }
            br.close();
     }catch (IOException e) {
            LOGGER.error(message);
     }
  }
于 2014-09-21T08:14:19.477 回答
1

春天

    private String readResource(String fileName){
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    Resource resource = resourceLoader.getResource("resourceSubfolder/"+fileName)
    try{
         Reader reader = new InputStreamReader(resource.getInputStream());
         return FileCopyUtils.copyToString(reader);
    } catch (IOException e){
         e.printStackTrace();
    }
    return null;
    }
于 2021-04-05T18:15:06.520 回答