13

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

4 Answers 4

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.

0
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?

1
  • I also needed to do this to load the spring context in a Jenkins plugin.
    – Dana
    Jan 27, 2016 at 20:20
0

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

3
  • 1
    This class does not let you pass in the class loader. This is not a correct answer.
    – JustinKSU
    Mar 29, 2016 at 19:22
  • The ClassPathXmlApplicationContext being a subclass of DefaultResourceLoader, it inherits the setClassloader method. So you can actually pass your class loader. Apr 4, 2016 at 12:30
  • This is true, but you do not inherit constructors. You can only use the ones declared on the class (docs.spring.io/spring/docs/current/javadoc-api/org/…)
    – JustinKSU
    Apr 4, 2016 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);
        
        
       
    }
    
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.