Resource(2)

本文详细介绍了Spring框架中不同类型的资源加载方式,包括ByteArrayResource、InputStreamResource、FileSystemResource、ClassPathResource和UrlResource等,每种资源类型都有具体的实现示例。

ResourceUtil

ResourceUtil.java

package com.test;

import java.io.IOException;
import java.io.InputStream;

import org.springframework.core.io.Resource;

public class ResourceUtil {
private static InputStream is=null;
public static void stream(Resource resource ){
    try {
        //获取文件资源输入流
        is=resource.getInputStream();
        //读取资源
        byte[] byteArray=new byte[is.available()];
        is.read(byteArray);
        System.out.println(new String(byteArray));
    } catch (IOException e) {
        e.printStackTrace();
    }
    finally{
        try {
        //关闭流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
}

ByteArrayResource

在ByteArrayResource中可以知道getInputStream()返回的是一个ByteArrayInputStream

ByteArrayResource.class

  public InputStream getInputStream()
    throws IOException
  {
    return new ByteArrayInputStream(this.byteArray);
  }

ByteArrayResourceTest .java

package com.test;

import org.junit.Test;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;

public class ByteArrayResourceTest {
    @Test
    public void byteArrayResourceTest(){
        Resource resource=new ByteArrayResource("Hello".getBytes());
        if(resource.exists()){
            ResourceUtil.stream(resource);
        }

    }
}

InputStreamResource

InputStreamResource的getInputStream()返回的是一个InputStream
并且this.read设置为true,即流只能读一次

InputStreamResource.class

  public InputStream getInputStream()
    throws IOException, IllegalStateException
  {
    if (this.read) {
      throw new IllegalStateException("InputStream has already been read - do not use InputStreamResource if a stream needs to be read multiple times");
    }

    this.read = true;
    return this.inputStream;
  }

InputStreamResourceTest.java

package com.test;

import java.io.ByteArrayInputStream;

import org.junit.Test;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;

public class InputStreamResourceTest {
    @Test
    public void inputStreamResourceTest(){
        ByteArrayInputStream inputStream=new ByteArrayInputStream("Hello!!!".getBytes());

        Resource resource=new InputStreamResource(inputStream); 
        if(resource.exists()){
            ResourceUtil.stream(resource);
        }

    }
}

FileSystemResource

FileSystemResource的getInputStream()返回的是一个FileInputStream字节流
并且不限读次数

FileSystemResourceTest.java

package com.test;

import java.io.File;

import org.junit.Test;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class FileSystemResourceTest {
    @Test
    public void  FileSystemResourceTest(){
        File file=new File("d:/a.txt"); 
        Resource resource=new FileSystemResource(file); 
        if(resource.exists()){
            ResourceUtil.stream(resource);      
        }

    }
}

ClassPathResource

三个构造方法替代了Class类和ClassLoader类的加载类路径资源的方法

  • public ClassPathResource(String path)
    使用的是默认的ClassLoader(ClassUtils.getDefaultClassLoader())加载“path”类路径资源;

  • public ClassPathResource(String path, ClassLoader classLoader)
    使用指定的ClassLoader加载“path”类路径资源,例如:比如当前类路径为”com.fsl.test”,需要加载的资源路径为”com/fsl/test.properties”,则将加载的资源在”com/fsl/test.properties”;

  • public ClassPathResource(String path, Class<?> clazz)
    使用指定类加载”path”类路径资源,例如:比如当前类路径为”com.fsl.test”,需要加载的资源路径为”com/fsl/test.properties”,则将加载的资源在”com/fsl/com/fsl/test.properties”;若需要加载资源路径为“test.properties”,则将加载的资源在”com/fsl/test.properties”

ClassPathResource.class

  public ClassPathResource(String path)
  {
    this(path, (ClassLoader)null);
  }

  public ClassPathResource(String path, ClassLoader classLoader)
  {
    Assert.notNull(path, "Path must not be null");
    String pathToUse = StringUtils.cleanPath(path);
    if (pathToUse.startsWith("/")) {
      pathToUse = pathToUse.substring(1);
    }
    this.path = pathToUse;
    this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
  }

  public ClassPathResource(String path, Class<?> clazz)
  {
    Assert.notNull(path, "Path must not be null");
    this.path = StringUtils.cleanPath(path);
    this.clazz = clazz;
  }
  • 使用默认的ClassLoader

ClassPathResourceTest.java

package com.test;

import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class ClassPathResourceTest {
    @Test
    public void  FileSystemResourceTest(){
        Resource resource=new ClassPathResource("com/test/test.properties");
        if(resource.exists()){
            ResourceUtil.stream(resource);      
        }

    }
}
  • 使用指定的ClassLoader

ClassPathResourceTest.java

package com.test;

import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class ClassPathResourceTest {
    @Test
    public void  FileSystemResourceTest(){
        ClassLoader cl=this.getClass().getClassLoader();
        Resource resource=new ClassPathResource("com/test/test.properties",cl);
        if(resource.exists()){
            ResourceUtil.stream(resource);      
        }

    }
}
  • 使用指定类,即相对于指定类的路径

ClassPathResourceTest.java

package com.test;

import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class ClassPathResourceTest {
    @Test
    public void  FileSystemResourceTest(){
        Class c=this.getClass();
        Resource resource=new ClassPathResource("test.properties",c);
        if(resource.exists()){
            ResourceUtil.stream(resource);      
        }

    }
}
  • 加载jar包里的资源,当在当前路径找不到后,才到jar包里找,并且返回第一个在jar包里找到的资源

ClassPathResourceTest.java

package com.test;

import java.io.File;

import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class ClassPathResourceTest {
    @Test
    public void  FileSystemResourceTest(){
        Resource resource=new ClassPathResource("test.properties");
        if(resource.exists()){
            ResourceUtil.stream(resource);      
        }

    }
}



能在当前类路径找到
输出结果
这里写图片描述
System.out.println(resource.getURL());
打印file:/F:/workspace-nyj/Spring_1/bin/test.properties


然后删除此test.properties,随便在一个jar包中添加test.properties用于测试
这里写图片描述
输出结果
这里写图片描述
System.out.println(resource.getURL());
打印jar:file:/F:/workspace-nyj/Spring_1/kaptcha-2.3.2.jar!/test.properties


记得资源不存在于文件系统中,而是存在jar包中。所以ClassPtahResource不能用getfile(),而应用getURL()

UrlResource

http:通过标准的http协议,访问web资源
ftp:通过标准的ftp协议,访问web资源
file:通过file协议访问本地文件资源系统

UrlResourceTest .java

package com.test;

import java.io.File;
import java.net.MalformedURLException;

import org.junit.Test;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;

public class UrlResourceTest {
    @Test
    public void  UrlResourceTest(){
        Resource resource;
        try {
            resource = new UrlResource("file:d:/a.txt");
            if(resource.exists()){
                ResourceUtil.stream(resource);      
            }
            resource=new UrlResource("http://www.baidu.com");
            if(resource.exists()){
                ResourceUtil.stream(resource);      
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 


    }
}
其实: @TableField(exist = false) @JsonProperty("assessment_id1") @JSONField(name = "assessment_id1") private String assessmentId1; @TableField(exist = false) @JsonProperty("resource_type1") @JSONField(name = "resource_type1") private String resourceType1; @TableField(exist = false) @JsonProperty("f_spare1") @JSONField(name = "f_spare1") private String fSpare1; @TableField(exist = false) @JsonProperty("f_tools1") @JSONField(name = "f_tools1") private String fTools1; @TableField(exist = false) @JsonProperty("f_resource1") @JSONField(name = "f_resource1") private String fResource1; @TableField(exist = false) @JsonProperty("f_technology1") @JSONField(name = "f_technology1") private String fTechnology1; @TableField(exist = false) @JsonProperty("f_data1") @JSONField(name = "f_data1") private String fData1; @TableField(exist = false) @JsonProperty("eletronic_resource1") @JSONField(name = "eletronic_resource1") private String eletronicResource1; @TableField(exist = false) @JsonProperty("remark1") @JSONField(name = "remark1") private String remark1; @TableField(exist = false) @JsonProperty("assessment_id2") @JSONField(name = "assessment_id2") private String assessmentId2; @TableField(exist = false) @JsonProperty("resource_type2") @JSONField(name = "resource_type2") private String resourceType2; @TableField(exist = false) @JsonProperty("f_spare2") @JSONField(name = "f_spare2") private String fSpare2; @TableField(exist = false) @JsonProperty("f_tools2") @JSONField(name = "f_tools2") private String fTools2; @TableField(exist = false) @JsonProperty("f_resource2") @JSONField(name = "f_resource2") private String fResource2; @TableField(exist = false) @JsonProperty("f_technology2") @JSONField(name = "f_technology2") private String fTechnology2; @TableField(exist = false) @JsonProperty("f_data2") @JSONField(name = "f_data2") private String fData2; @TableField(exist = false) @JsonProperty("eletronic_resource2") @JSONField(name = "eletronic_resource2") private String eletronicResource2; @TableField(exist = false) @JsonProperty("remark2") @JSONField(name = "remark2") private String remark2; }这些字段是同一个其他类的: @Data @TableName("security_assessment_resource") public class SecurityAssessmentResourceEntity { @TableId(value = "f_id") @JsonProperty("f_id") @JSONField(name = "f_id") private String id; @TableField(value = "assessment_id") @JsonProperty("assessment_id") @JSONField(name = "assessment_id") private String assessmentId; @TableField(value = "resource_type") @JsonProperty("resource_type") @JSONField(name = "resource_type") private String resourceType; @TableField(value = "f_spare") @JsonProperty("f_spare") @JSONField(name = "f_spare") private String fSpare; @TableField(value = "f_tools") @JsonProperty("f_tools") @JSONField(name = "f_tools") private String fTools; @TableField(value = "f_resource") @JsonProperty("f_resource") @JSONField(name = "f_resource") private String fResource; @TableField(value = "f_technology") @JsonProperty("f_technology") @JSONField(name = "f_technology") private String fTechnology; @TableField(value = "f_data") @JsonProperty("f_data") @JSONField(name = "f_data") private String fData; @TableField(value = "eletronic_resource") @JsonProperty("eletronic_resource") @JSONField(name = "eletronic_resource") private String eletronicResource; @TableField(value = "remark") @JsonProperty("remark") @JSONField(name = "remark") private String remark; @TableField(value = "create_time", fill = FieldFill.INSERT) @JsonProperty("create_time") @JSONField(name = "create_time") private Date createTime; @TableField(value = "update_time", fill = FieldFill.UPDATE) @JsonProperty("update_time") @JSONField(name = "update_time") private Date updateTime; }。相当于是有两个其他类,现在我需要你帮我写一个方法。我传入第一个类。你帮我生成两个第二个类的数据且存储到数据库。assessment_id表示第一个类的id。然后他们自己的id使用RandomUtil.uuId();来创建存储。
最新发布
11-30
# 将主类数据拆分为两个资源类并存储的方法 以下是根据您的需求实现的方法,将第一个类的数据拆分为两个`SecurityAssessmentResourceEntity`对象并存储到数据库: ```java @Service public class SecurityAssessmentResourceService { @Autowired private SecurityAssessmentResourceMapper resourceMapper; @Autowired private RandomUtil randomUtil; // 假设您有一个随机ID生成工具类 /** * 将主评估类拆分为两个资源类并保存到数据库 * @param assessment 主评估类对象 * @return 保存是否成功 */ @Transactional public boolean saveAssessmentResources(SecurityAssessmentEntity assessment) { if (assessment == null || StringUtils.isBlank(assessment.getId())) { return false; } // 创建第一个资源对象 SecurityAssessmentResourceEntity resource1 = new SecurityAssessmentResourceEntity(); convertToResource(assessment, "1", resource1); // 创建第二个资源对象 SecurityAssessmentResourceEntity resource2 = new SecurityAssessmentResourceEntity(); convertToResource(assessment, "2", resource2); // 保存到数据库 return resourceMapper.insert(resource1) > 0 && resourceMapper.insert(resource2) > 0; } /** * 将主类属性转换到资源类 * @param assessment 主类对象 * @param suffix 属性后缀("1"或"2") * @param resource 目标资源对象 */ private void convertToResource(SecurityAssessmentEntity assessment, String suffix, SecurityAssessmentResourceEntity resource) { resource.setId(randomUtil.uuid()); // 生成新的ID resource.setAssessmentId(assessment.getId()); // 设置关联的评估ID // 使用反射动态获取带后缀的属性值 try { String resourceType = (String) getFieldValue(assessment, "resourceType" + suffix); String fSpare = (String) getFieldValue(assessment, "fSpare" + suffix); String fTools = (String) getFieldValue(assessment, "fTools" + suffix); String fResource = (String) getFieldValue(assessment, "fResource" + suffix); String fTechnology = (String) getFieldValue(assessment, "fTechnology" + suffix); String fData = (String) getFieldValue(assessment, "fData" + suffix); String eletronicResource = (String) getFieldValue(assessment, "eletronicResource" + suffix); String remark = (String) getFieldValue(assessment, "remark" + suffix); // 设置资源对象属性 resource.setResourceType(resourceType); resource.setFSpare(fSpare); resource.setFTools(fTools); resource.setFResource(fResource); resource.setFTechnology(fTechnology); resource.setFData(fData); resource.setEletronicResource(eletronicResource); resource.setRemark(remark); // 创建时间和更新时间由数据库自动填充 } catch (Exception e) { throw new RuntimeException("转换资源对象属性时出错", e); } } /** * 使用反射获取字段值 */ private Object getFieldValue(Object obj, String fieldName) throws Exception { Field field = obj.getClass().getDeclaredField(fieldName); field.setAccessible(true); return field.get(obj); } } ``` ## 使用说明 1. **调用方式**: ```java SecurityAssessmentEntity assessment = // 获取主评估对象 boolean success = securityAssessmentResourceService.saveAssessmentResources(assessment); ``` 2. **方法特点**: - 自动为主类中的两组资源属性(带1和2后缀)创建两个资源对象 - 使用UUID为每个资源对象生成唯一ID - 保留主类ID作为关联字段(assessment_id) - 使用反射动态获取带数字后缀的字段值 - 添加事务注解确保数据一致性 3. **依赖项**: - MyBatis-Plus的Mapper接口 - 随机ID生成工具(如Hutool的RandomUtil) - Spring的事务管理 ## 优化建议 1. 如果性能要求高,可以改为硬编码属性访问,避免反射开销 2. 可以添加参数校验和日志记录 3. 考虑添加批量保存的版本 4. 可以返回保存后的资源对象ID列表,而不是简单的boolean
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值