使用特定的类加载器加载Spring上下文

13

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

4个回答

15

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

DefaultResourceLoader有一个构造函数,您可以在其中指定类加载器,并且还有一个setClassLoader方法。

因此,您的任务是找到所需的Spring上下文加载器的构造函数,您可以在其中指定类加载器,或者只需创建它并使用setClassLoader方法来设置您想要的类加载器。


6
    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目的而执行此操作,请参见此处:如何在OSGi捆绑包中使用Spring bean?


我也需要这样做来在 Jenkins 插件中加载 Spring 上下文。 - Dana

0

正在使用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);
        
        
       
    }
    
}

0

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


1
这个类不允许你传入类加载器。这不是正确的答案。 - JustinKSU
ClassPathXmlApplicationContext是DefaultResourceLoader的子类,因此它继承了setClassLoader方法。所以你实际上可以传递你的类加载器。 - sebastiencol
这是正确的,但你不能继承构造函数。你只能使用在类上声明的构造函数。(https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/support/ClassPathXmlApplicationContext.html) - JustinKSU

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接