如何在Spring中加载资源并将其内容用作字符串

时间:2012-12-24 14:58:37

标签: java spring

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

资源包含自由文本。

6 个答案:

答案 0 :(得分:31)

<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>

答案 1 :(得分:21)

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

def ecpd(request):
     r= requests.get('http://jira.xxx.xxx.com/rest/api/2/issue/key-XXX',auth=HTTPBasicAuth('user','pass'),headers = {'Content-Type' : 'application/json'})
    if r.status_code == 200:
         jsonDict = r.json()
         return HttpResponse(jsonDict)

答案 2 :(得分:12)

请阅读:

    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);
    }

答案 3 :(得分: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>

答案 4 :(得分: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);
     }
  }

答案 5 :(得分: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;
    }