【问题标题】:Loading Spring context with specific classloader使用特定的类加载器加载 Spring 上下文
【发布时间】:2011-04-14 07:49:17
【问题描述】:

如何使用我自己的 ClassLoader 实例加载 Spring 上下文?

【问题讨论】:

    标签: spring classloader


    【解决方案1】:

    许多 Spring 上下文加载器(例如 ClassPathXmlApplicationContext ) 是DefaultResourceLoader 的子类。

    DefaultResourceLoader 有一个constructor,您可以在其中指定类加载器,还有一个setClassLoader 方法。

    所以你的任务是找到你需要的 Spring Context Loader 的构造函数,你可以在其中指定类加载器,或者只是创建它,然后使用集合来设置你想要的类加载器。

    【讨论】:

      【解决方案2】:
          final ClassLoader properClassLoader = YourClass.class.getClassLoader();
      
          appContext = new ClassPathXmlApplicationContext("application-context.xml") {
      
              protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader) {
                  super.initBeanDefinitionReader(reader);
                  reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
                  reader.setBeanClassLoader(properClassLoader);
                  setClassLoader(properClassLoader);
      

      如果您出于 OSGI 目的执行此操作,请参见此处:How do I use a Spring bean inside an OSGi bundle?

      【讨论】:

      • 我还需要这样做才能在 Jenkins 插件中加载 spring 上下文。
      【解决方案3】:

      org.springframework.context.support.ClassPathXmlApplicationContext 课程在这里为您服务。

      【讨论】:

      • 这个类不允许你传入类加载器。这不是一个正确的答案。
      • ClassPathXmlApplicationContext 是 DefaultResourceLoader 的子类,它继承了 setClassloader 方法。所以你实际上可以传递你的类加载器。
      • 这是真的,但你不继承构造函数。您只能使用在类上声明的那些 (docs.spring.io/spring/docs/current/javadoc-api/org/…)
      【解决方案4】:

      正在使用spring boot并想使用自定义类加载器创建应用程序上下文的人可以这样做:

      @SpringBootApplication
      public class Application
      {
      
      public static void main(String[] args) {
        
              
              SpringApplication app =
                  new SpringApplication(Application.class);
              
              ResourceLoader resourceLoader = new DefaultResourceLoader();
      
              YourClassLoaderObject yourClassLoaderObject = new YourClassLoaderObject();
      
              ((DefaultResourceLoader)resourceLoader).setClassLoader(yourClassLoaderObject);
                      
              app.setResourceLoader(resourceLoader);
              
              context = app.run(args);
              
              
             
          }
          
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-03
        • 1970-01-01
        • 2011-09-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多