Поддержка пространства имен
Чтобы реализовать поддержку пространства имен, она должна быть унаследована от имен -пространственно -чистого пространства.
пакет com.codestd.spring.cxf.config.schema; import org.springframework.beans.factory.xml.namespacehandlersupport; импорт com.codestd.spring.cxf.config.endpointbeanprocessor;/*** Обработка namespace* @author jaune (wang chengwe); Класс WebserviceannotationNamespaceHandler расширяет именам пространства именудлерсуппора {@OverridePublic void init () {// todo Автогенерированный метод stubThis.registerbeandefinitionParser («Annotation-endpoint», New AnnotationBeanditionParser («Endpointbeanprass.cessoint»);Используйте метод RegisterBeandefinitionParser, чтобы объяснить поддержку конфигурации, добавленную в Spring. Annotation-Endpoint-это элемент, который поддерживается конфигурацией. AnnotationBeandefinitionParser - это класс, который обрабатывает конфигурацию. EndPointbeanProcessor - это класс, который обрабатывает бобовые аннотированные @endpoint, и будет подробно описан позже.
Конфигурация обработки
Необходимо реализовать BeandefinitionParser
пакет com.codestd.spring.cxf.config.schema; import org.springframework.beans.factory.config.beandefinition; импорт org.springframework.beans.factory.support.rootbeandefinition; импорт org.spramework.beans.factory.s.beanfintorition; импорт org.spramework.beans.factory. org.springframework.beans.factory.xml.ParserContext;import org.springframework.util.StringUtils;import org.w3c.dom.Element;/*** @author jaune(Wang Chengwei)* @since 1.0.0*/public class AnnotationBeanDefinitionParser implements BeanDefinitionParser {private final Класс <?> Beanclass; public annotationbeandefinitionparser (class <?> Beanclass) {this.beanclass = beanclass;}@переопределяемый проход Beandefinition (элемент элемент, parsercontext parsercontext) {rootbeandefinition beandefinition = new Rootbeandefinition ();; beandefinition.setbeanclass (beanclass); beandefinition.setlazyinit (false); string id = element.getattribute ("id"); if (id = null || id.length () == 0) {string = element.getattribut beanclass.getname ();} if (parsercontext.getregistry (). Содержит Beandefinition (id)) {Throw new allodalStateException ("дубликат идентификатор пружинного боба" + id);} parserContextext.getRegistry (). element.getAttribute ("package"); if (! stringutils.isempty (annotationpackage)) beandefinition.getpropertyvalues (). add ("annotationpackage", annotationpackage); return beandefinition;}}Для применения BeandefinitionParser, пожалуйста, обратитесь к официальной весенней документации.
Класс инструментов регистрации бобов
пакет com.codestd.spring.cxf.config; import org.springframework.beans.beansexception; import org.springframework.beans.factory.config.beandefinition; импорт org.springframework.beans.factory.support.beandefinition; org.springframework.beans.factory.support.beandefinitionregistry; импорт org.springframework.context.applicationcontext; импорт org.springframework.context.applicationcontextaware; import org.springframework.context.configuplablicalecomer; Необходимо внедрить Spring ApplicationContext.* @Author jaune (Wang chengwei)* @since 1.0.0*/public class. = ApplicationContext; if (ApplicationContext EncanceOf configurableApplicalationContext) {this.ConfigurableApplicationContext = (configurableApplicamationContext) this.ApplicationContext;}} public beanRegistry () {} public BeanRegistry (ApplicationContextextext) {this.seplicationContext (applicationContext); clazz) {if (configurableApplicalationContext == null) return null; BeandefinitionRegistry beandefinitonregistry = (beandefinitionregistry) configurableapplicationcontext.getbeanfactory (); beandefinitionbuilder beandefinitionbuilder = это. = beandefinitionbuilder.getrawbeandefinition (); beandefinitonregistry.registerbeandefinition (clazz.getName (), beandefinition); return beandefinition;} Частный BeandefinitionBuilder CreativeBuilder (класс <?> clazz) (Beandefinitionbuilder (класс <?> clazz) {beandefinitionbuilder (Class <?> clazz) {beandefinitionbuilder BeandefinitionBuilder.genericBeandefinition (clazz); return beandefinitionbuilder;}}Обработка @endpoint
пакет com.codestd.spring.cxf.config; import org.springframework.beans.beansexception; import org.springframework.beans.factory.disposablebean; импорт org.springframework.beans.factory.config.beanfactorypostprocsors; org.springframework.beans.factory.config.configurablelistablebeanfactory; import org.springframework.beans.factory.support.beandefinitionRegistry; import org.springframework.context.application context; import org.spramework.context.application.application context; import.spramework.context.application.application context; org.springframework.context.annotation.classpathbeandefinitionscanner; Import org.springframework.core.type.filter.annotationtypefilter; импорт org.springframework.util.Stringutils; импорт com.codestd.spring.cxf.annotation.end Jaune (Wangchengwei)* @since 1.0.0.0*/public Class EndpointbeanProcessor реализует BeanFactoryPostProcessor, issoblebean, beanpostprocessor, ApplicationContextaware {Private Final String Comma_split_pattern = ","; Private ApplicateContexteContextectore {Private StringPackAge intrestAge stringSegages; Beanregistry; public void setannotationpackage (string annotationpackage) {this.annotationpackage = annotationpackage; if (! stringUtils.isempty (this.annotationpackage)) this.annotationpackages = @annotationpackage.split (this.com_split_pathern); ApplicationContext) Throws BeanSexception {this.ApplicationContext = ApplicationContext; this.beanregistry = new Beanregistry (this.applicationContext);}@overridePublic Object postprocessafterinitialization (объект Bean, String Beanname) Throws Beansexception {if (! this.ismatchpackage (bean)) вернуть bean; endpoint endpoint = bean.getclass (). getannotation (endpoint. null) {system.out.println (bean.getclass ());} return bean;} @overridepublic obj ismatchpackage (Object Bean) {if (annotationPackages == null || annotationpackages.length == 0) {return true;} String beanclassname = bean.getClass (). getName (); for (string pkg: annotationpackages) {if (beanclassname.startswith (pkg) {return {return) {return) {pkg). false;}/*** scan {@link com.codestd.spring.cxf.annotation.endpoint} аннотация*/@overridepublic void pospocessbeanfactory (configureblelistablebeanfactory beanfactory) throws {if (annotationpackage == null || annotatory. {return;} if (beanfactory cansess of beandefinitionregistry) {beandefinitionregistry beandefinitionregistry = (beandefinitionregistry) beanfactory; classpathbeandefinitionscanner scanner = annotationtypefipfilepefificscanner (BeandefinitionRegistry, true); AnnotationTyPefilter (endpoint.class); scanner.addincludefilter (filter); scanner.scan (annotationpackages);}}} Сканирование аннотаций было реализовано здесь. Затем вам необходимо написать код обработки бизнеса в методе постпроцессафтеринициализации. Послеинализация означает, что бобы были созданы и введены атрибутами.
Постпроцесс, предварительная, в основном используется для внедрения свойств при экземпляре фасоли.
Пусть весна распознает расширения
Сначала создать Spring.handlers в Meta-Inf в Classpath, контент выглядит следующим образом
http/: //www.codestd.com/schema/std/ws=com.codestd.spring.cxf.config.schema.webserviceannotationnamespacehandler
В этом файле укажите, какой класс нуждается в пространстве имен.
Затем создайте Spring.schemas
http/: //www.codestd.com/schema/std/ws/stdws-1.0.xsd=meta-inf/schema/stdws-1.0.xsd=meta-inf/schema/stdws-1.0.xsd
Укажите местоположение файла SECHMA, Spring будет использовать файл XSD, сформулированный здесь, чтобы убедиться, что конфигурация верна.
тест
Создать интерфейс
Пакет com.codestd.spring.cxf.ws; import javax.jws.webservice;/*** @author jaune (wang chengwei)*@since 1.0.0*/@webservicepublic interface helloservice {public String syhi (String name);}Класс реализации
Пакет com.codestd.spring.cxf.ws; import javax.jws.webservice; import com.codestd.spring.cxf.annotation.endpoint;/*** @author jaune (wang chengwei)*@since 1.0.0*/ @endpoint (адрес = "helloservice", id = @since 1.0.0*/ @ «HelloServiceendPoint»)@Webservice (endPointInterface = "com.codestd.spring.cxf.ws.helloService") открытый класс HelloServiceImpl реализует HelloService {@OverridePublic String Syhi (String name) {return "Hello"+}}}}}}}}}}}}}}}}}}}}Тестовые случаи
@Runwith (springjunit4classrunner.class) @contextconfiguration (locations = {"classPath: ApplicationContext.xml"}) открытый класс инициализация. В классе обработки есть часть кода, который печатает все классы с аннотацией @endpoint, поэтому, если имя класса распечатано, это означает, что конфигурация нормальная.
Запустите тестовые примеры
Консоль может видеть
Класс com.codestd.spring.cxf.ws.helloserviceimpl
Благодаря введению приведенного выше контента это расширение в основном реализовано.