Spring Boot ClassLoader

     在使用javaagent+javassist作agent监控Spring Boot项目时,在IDE中正常运行,但是打包成jar之后则发生nosuchclassfound错误,下面对此产生的原因做一些解析。

1.  JVM类加载

JVM类采用的是双亲委托类加载机制。类的加载过程:

  1.   当前类加载器已经加载,则返回类,否则委托父加载器加载此类;
  2.   父加载器执行1的步骤知道Bootstrap ClassLoader
  3.   如果Bootstrap ClassLoader未加载,则由最开始的类加载器加载类。

其中Bootstrap ClassLoader所加载的是$JAVA_HOME/jre/lib下的jar包和class,ExtClassLoader加载$JAVA_HOME/jre/lib/ext中的jar包,AppClassLoader是加载java.class.path下的类和jar包。

父类加载器所加载的类可以被子类加载器所加载的类使用,但是子类加载器加载的类不能被父类加载器加载的类访问。

2. IDE(Idea)

Spring Boot项目在IDE(idea)中运行&#x

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Spring Boot默认会将静态资源文件(如txt文件)放在classpath下的/static、/public和/resources目录中,可以直接访问。以下是几种读取txt静态文件的方法: 1. 使用ClasspathResourceLoader:在Spring Boot中,可以通过ClasspathResourceLoader类来读取classpath下的文件。可以通过以下代码来读取txt文件: ```java ClassLoader classLoader = getClass().getClassLoader(); Resource resource = new ClassPathResource("static/example.txt"); try { File file = resource.getFile(); // 读取文件内容 } catch (IOException e) { e.printStackTrace(); } ``` 2. 使用ResourceLoader:在Spring Boot中,可以通过ResourceLoader来加载classpath下的文件。可以通过以下代码来读取txt文件: ```java @Autowired private ResourceLoader resourceLoader; public void readTxtFile() { Resource resource = resourceLoader.getResource("classpath:static/example.txt"); try { InputStream inputStream = resource.getInputStream(); // 读取文件内容 inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } ``` 3. 使用文件路径:如果txt文件位于绝对路径下,可以直接使用File类来读取。可以通过以下代码来读取txt文件: ```java String filePath = "/absolute/path/to/example.txt"; File file = new File(filePath); try { BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while ((line = reader.readLine()) != null) { // 读取文件内容 } reader.close(); } catch (IOException e) { e.printStackTrace(); } ``` 以上是使用Spring Boot读取txt静态文件的几种方法,根据具体情况选择合适的方法来实现。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值