开发者

Loading Spring context with specific classloader

How can I go about开发者_StackOverflow社区 loading a Spring context with my own ClassLoader instance?


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.


    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?


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


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);
        
        
       
    }
    
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜