使用 Spring ResourcePatternResolver 读取指定路径下的类信息

通过 Spring 提供的Api ResourcePatternResolver 读取指定classpath下面的类信息。
示例代码:


import org.junit.Test;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.util.SystemPropertyUtils;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Arrays;

import static org.springframework.core.io.support.ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX;

/**
 * @desc: Desc
 * @author: wangyingjie1
 * @date: 2018/1/29 18:16
 * To change this template use File | Settings | File and Code Templates | Includes | File Header.
 */
public class ResourcePatternResolverTest {

    private static final String basePackage = "com.jd.controller";

    public static final String DEFAULT_RESOURCE_PATTERN = "/**/*";

    @Test
    public void testReadResource() throws IOException {
        //获取Spring资源解析器
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

        //获取packageSearchPath下的Resource,这里得到的Resource是Class信息
        Resource[] resources = resourcePatternResolver.getResources(CLASSPATH_ALL_URL_PREFIX
                + ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage))
                + DEFAULT_RESOURCE_PATTERN + ClassUtils.CLASS_FILE_SUFFIX);

        Arrays.stream(resources).forEach(resource -> {
            System.out.println("=======>" + resource.getFilename());
        });


        parseClazz(resources, resourcePatternResolver);
    }

    private void parseClazz(Resource[] resources, ResourcePatternResolver resourcePatternResolver)  throws IOException {

        //创建Spring中用来读取class的工厂
        MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

        for (Resource resource : resources) {
            //检查resource,
            String fullClassName = null;
            if (resource.isReadable()) {
                MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                if (metadataReader != null) {
                    fullClassName = metadataReader.getClassMetadata().getClassName();
                }
            }

            try {
                Class<?> clazz = Class.forName(fullClassName);
                //方式1
                Annotation myAnnotation = clazz.getAnnotation(Controller.class);

                //方式2
                Controller annotation = AnnotationUtils.findAnnotation(clazz, Controller.class);

                System.out.println("an===========>" + annotation );
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                throw new RuntimeException(" check package path", e);
            }
        }
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中,你可以使用`Resource`和`InputStream`来读取指定路径的文件,并将文件内容返回为文件流。以下是一个示例代码: ```java import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @RestController public class FileController { @GetMapping("/file/{filename}") public ResponseEntity<Resource> getFile(@PathVariable String filename) throws IOException { // 指定文件路径 String filePath = "/path/to/your/file/" + filename; // 创建文件资源对象 Resource resource = new FileSystemResource(filePath); // 检查文件是否存在 if (!resource.exists()) { return ResponseEntity.notFound().build(); } // 获取文件输入流 InputStream inputStream = resource.getInputStream(); // 返回文件流 return ResponseEntity.ok() .contentLength(Files.size(Paths.get(filePath))) .header("Content-Disposition", "attachment; filename=\"" + filename + "\"") .body(new InputStreamResource(inputStream)); } } ``` 在上述代码中,你需要将`/path/to/your/file/`替换为实际存储文件的路径。当访问`/file/{filename}`时,该方法会检查文件是否存在,然后将文件内容返回为文件流。 请注意,上述示例假设文件路径是绝对路径。如果你需要处理相对路径或基于路径的文件,请使用适当的方法获取资源。 希望这对你有所帮助!如果你有任何其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值