How to use custom NamespaceHandlerResolver when creating XML ApplicationContext?

∥☆過路亽.° 提交于 2019-12-12 02:59:56

问题


I would like to use a custom NamespaceHandlerResolver when creating a spring application context from xml.

The spring documentation only explains how to create custom NamespaceHandler. But I need to use a specifically initialized NamespaceHandlerResolver in order to get the NamespaceHandlers I need to use corretly initialized (NamespaceHandlers are context dependent).

So when creating an xml applicationcontext, how to set a custom NamespaceHandlerResolver?


回答1:


One needs to create an application context derived from org.springframework.context.support.AbstractXmlApplicationContext and must override initBeanDefinitionReader(XmlBeanDefinitionReader reader). The override should set the custom NamespaceHandlerResolver to the reader instance.

import org.springframework.beans.factory.xml.NamespaceHandlerResolver;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CustomNamespaceHandlerClassPathXmlApplicationContext extends ClassPathXmlApplicationContext {

    private NamespaceHandlerResolver customNamespaceHandlerResolver;

    @Override
    protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader) {
        super.initBeanDefinitionReader(reader);
        reader.setNamespaceHandlerResolver(customNamespaceHandlerResolver);
    }

    public void setCustomNamespaceHandlerResolver(
            NamespaceHandlerResolver customNamespaceHandlerResolver) {
        this.customNamespaceHandlerResolver = customNamespaceHandlerResolver;
    }
}


来源:https://stackoverflow.com/questions/34697960/how-to-use-custom-namespacehandlerresolver-when-creating-xml-applicationcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!