zoukankan      html  css  js  c++  java
  • 04点睛Spring4.1-资源调用

    转发:https://www.iteye.com/blog/wiselyman-2210666

    4.1 Resource

    • spring用来调用外部资源数据的方式
    • 支持调用文件或者是网址
    • 在系统中调用properties文件可参考<<02点睛Spring4.1-Java Config>>中结合@PropertySourceEnvironment来使用
    • 也可以使用@Value来注入资源,@Value的使用将在<<13点睛Spring4.1-Spring EL>>章节中有更详细的使用

    4.2 示例

    4.2.1 新增commons-io到maven依赖

    需使用commons-io的IOUtils工具类将InputStream转换成String 在pom.xml的中添加如下

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.3</version>
    </dependency>
    

    4.2.2 新建测试用info.txt

    sadfasdfasdfasdfasdfsad
    sadfasdfasdfasdfasdfsad
    sadfasdfasdfasdfasdfsad

    4.2.3 测试

    package com.wisely.resource;
    
    import java.io.IOException;
    
    import org.apache.commons.io.IOUtils;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    import org.springframework.core.io.Resource;
    import org.springframework.core.io.UrlResource;
    import org.springframework.stereotype.Component;
    
    @Component
    public class Main {
        @Value("classpath:com/wisely/resource/info.txt")
        private Resource info;
    
        public static void main(String[] args) throws IOException {
            AnnotationConfigApplicationContext context =
                            new AnnotationConfigApplicationContext("com.wisely.resource");
            Main main = context.getBean(Main.class);
            System.out.println(main.injectInfo());
            System.out.println("----------------------------");
    
            //classpath: spring的一个模拟协议,类似于http:
            Resource file = context.getResource("classpath:com/wisely/resource/info.txt");
            System.out.println(IOUtils.toString(file.getInputStream()));
            System.out.println("----------------------------");
    
            Resource url = (UrlResource) context.getResource("http://www.baidu.com");
            System.out.println(IOUtils.toString(url.getInputStream()));
            context.close();
        }
    
        public String injectInfo() throws IOException{
            return IOUtils.toString(info.getInputStream());
        }
    
    }
    
    

    输出结果

    sadfasdfasdfasdfasdfsad
    sadfasdfasdfasdfasdfsad
    sadfasdfasdfasdfasdfsad
    ----------------------------
    sadfasdfasdfasdfasdfsad
    sadfasdfasdfasdfasdfsad
    sadfasdfasdfasdfasdfsad
    ----------------------------
    <!DOCTYPE html><!--STATUS OK--><html><head>
  • 相关阅读:
    Object转bigdecimal
    如何在A用户下建立视图,这个视图是A的表与B的表进行关联的?
    java.util.Date和java.sql.Date的区别和相互转化(转)
    JAVA如何获取GUID
    详解Oracle DELETE和TRUNCATE 的区别(摘)
    分开显示Excel2010打开的文档
    CentOS实验三:使用安装光盘建立本地软件源
    基本C库函数
    Shell_2(验证符合的输入)
    Shell_1(目录之间切换执行脚本)
  • 原文地址:https://www.cnblogs.com/Jeely/p/11949825.html
Copyright © 2011-2022 走看看