How can I go about loading a Spring context with my own ClassLoader
instance?
Asked
Active
Viewed 2.3k times
13

Synesso
- 37,610
- 35
- 136
- 207
4 Answers
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?
-
I also needed to do this to load the spring context in a Jenkins plugin. – Dana Jan 27 '16 at 20:20
0
The org.springframework.context.support.ClassPathXmlApplicationContext
class is here for you.

sebastiencol
- 113
- 4
-
1This 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