13

How can I go about loading a Spring context with my own ClassLoader instance?

Synesso
  • 37,610
  • 35
  • 136
  • 207

4 Answers4

15

Many Spring Context Loader (for example ClassPathXmlApplicationContext ) are subclass of DefaultResourceLoader.

DefaultResourceLoader has a constructor where you can specify the Classloader and also has a setClassLoader method.

So it is your task to find a constructor of the Spring Context Loader you need, where you can specify the classloader, or just create it, and then use the set to set the classloader you want.

Ralph
  • 118,862
  • 56
  • 287
  • 383
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);

See here if you are doing this for OSGI purposes: How do I use a Spring bean inside an OSGi bundle?

Community
  • 1
  • 1
user64141
  • 5,141
  • 4
  • 37
  • 34
0

The org.springframework.context.support.ClassPathXmlApplicationContext class is here for you.

sebastiencol
  • 113
  • 4
  • 1
    This class does not let you pass in the class loader. This is not a correct answer. – JustinKSU Mar 29 '16 at 19:22
  • The ClassPathXmlApplicationContext being a subclass of DefaultResourceLoader, it inherits the setClassloader method. So you can actually pass your class loader. – sebastiencol Apr 04 '16 at 12:30
  • This is true, but you do not inherit constructors. You can only use the ones declared on the class (https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/support/ClassPathXmlApplicationContext.html) – JustinKSU Apr 04 '16 at 16:51
0

People who are using spring boot and wants to use custom classloader to create application context can do it like this:

@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);
        
        
       
    }
    
}
Vishwas Upadhyay
  • 182
  • 1
  • 12