自定义类加载器加载Spring

spring根本不会去管自己被放在哪里,它统统使用TCCL来加载类,而TCCL默认设置为了WebAppClassLoader,也就是说哪个WebApp应用调用了spring,spring就去取该应用自己的WebAppClassLoader来加载bean。这在真正理解线程上下文类加载器(多案例分析)中已有详细描述。
因此,为了使spring使用自定义的类加载器进行加载,需要开一个线程,将这个线程的类加载器设置为自定义类加载器。

    public String test(){
        try{
            // MyClassLoaderCustom 见 https://blog.csdn.net/qq_32506245/article/details/113059028
            MyClassLoaderCustom myClassLoaderCustom = new MyClassLoaderCustom(Thread.currentThread().getContextClassLoader().getParent());
            Callable<String> callable=()->{
                ApplicationContext ctx=new ClassPathXmlApplicationContext("application.xml");
                TestA testA=(TestA) ctx.getBean("com.example.TestA");
                return testA.getClass().getClassLoader().toString();
            };
            FutureTask<String> task=new FutureTask<>(callable);
            Thread thread=new Thread(task);
            // 设置线程上下文类加载器
            thread.setContextClassLoader(myClassLoaderCustom);
            thread.start();
            while (!task.isDone());
            return task.get();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;        
    }

参考网站

真正理解线程上下文类加载器(多案例分析)
saturn java 热加载(二)资源文件 spring & logback

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值