前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >聊聊自定义SPI如何使用自定义标签注入到spring容器中

聊聊自定义SPI如何使用自定义标签注入到spring容器中

作者头像
lyb-geek
发布2022-01-07 10:10:26
5510
发布2022-01-07 10:10:26
举报
文章被收录于专栏:Linyb极客之路Linyb极客之路

01

前言

之前我们聊过自定义的SPI如何与spring进行整合,今天我们就来聊下如何通过自定义标签将spi对象注入到spring容器中

02

实现套路

1、自定义xsd

示例

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:beans="http://www.springframework.org/schema/beans"
            xmlns:tool="http://www.springframework.org/schema/tool"
            xmlns="http://lybgeek.github.com/schema/spi"
            targetNamespace="http://lybgeek.github.com/schema/spi">

    <xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
    <xsd:import namespace="http://www.springframework.org/schema/beans"
                schemaLocation="http://www.springframework.org/schema/beans/spring-beans.xsd"/>
    <xsd:import namespace="http://www.springframework.org/schema/tool"/>

    <xsd:annotation>
        <xsd:documentation>
            <![CDATA[ Namespace support for spi services ]]></xsd:documentation>
    </xsd:annotation>


    <xsd:complexType name="scanType">
        <xsd:attribute name="id" type="xsd:ID">
            <xsd:annotation>
                <xsd:documentation><![CDATA[ The unique identifier for a bean. ]]></xsd:documentation>
            </xsd:annotation>
        </xsd:attribute>
        <xsd:attribute name="basePackages" type="xsd:string" use="required">
            <xsd:annotation>
                <xsd:documentation><![CDATA[ Specify the spi package name to scan, multiple scan packages are separated by commas ]]></xsd:documentation>
            </xsd:annotation>
        </xsd:attribute>
    </xsd:complexType>

    <xsd:complexType name="interceptorType">
        <xsd:attribute name="id" type="xsd:ID">
            <xsd:annotation>
                <xsd:documentation><![CDATA[ The unique identifier for a bean. ]]></xsd:documentation>
            </xsd:annotation>
        </xsd:attribute>
        <xsd:attribute name="class" type="xsd:string" use="required">
            <xsd:annotation>
                <xsd:documentation><![CDATA[ Interceptor class name]]></xsd:documentation>
            </xsd:annotation>
        </xsd:attribute>
    </xsd:complexType>

    <xsd:complexType name="interceptorChainType">
        <xsd:choice>
            <xsd:element ref="interceptor" minOccurs="1" maxOccurs="unbounded"/>
        </xsd:choice>
    </xsd:complexType>


    <xsd:element name="scan" type="scanType">
        <xsd:annotation>
            <xsd:documentation><![CDATA[ The scan config ]]></xsd:documentation>
        </xsd:annotation>
    </xsd:element>

    <xsd:element name="interceptor" type="interceptorType">
        <xsd:annotation>
            <xsd:documentation><![CDATA[ The interceptor config ]]></xsd:documentation>
        </xsd:annotation>
    </xsd:element>

    <xsd:element name="interceptorChain" type="interceptorChainType">
        <xsd:annotation>
            <xsd:documentation><![CDATA[ The interceptorChainType config ]]></xsd:documentation>
        </xsd:annotation>
    </xsd:element>

</xsd:schema>

ps: 如果对xsd不熟悉的朋友,可以参考如下链接

https://www.w3school.com.cn/schema/index.asp

2、自定义解析BeanDefinitionParser解析器

示例:

代码语言:javascript
复制
public class AnnotationBeanDefinitionParser implements BeanDefinitionParser {

    private final Class<?> beanClass;

    public AnnotationBeanDefinitionParser(Class<?> beanClass) {
        this.beanClass = beanClass;
    }

    @Override
    public BeanDefinition parse(Element element, ParserContext parserContext) {

        String packageToScan = element.getAttribute("basePackages");
        String[] packagesToScan = trimArrayElements(commaDelimitedListToStringArray(packageToScan));

        RootBeanDefinition beanDefinition = new RootBeanDefinition();
        beanDefinition.setBeanClass(beanClass);
        beanDefinition.setLazyInit(false);
        beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0,packagesToScan);
        String beanName = BeanUtils.generateBeanName(element,"id",parserContext,beanClass.getName());
        parserContext.getRegistry().registerBeanDefinition(beanName,beanDefinition);

        return beanDefinition;
    }


}

3、定义NamespaceHandler实现类处理自定义标签的处理器

示例:

代码语言:javascript
复制
public class SpiNamespaceHandler extends NamespaceHandlerSupport {

    @Override
    public void init() {
        registerBeanDefinitionParser("scan", new AnnotationBeanDefinitionParser(SpiAnnotationPostProcessor.class));
    }
}

4、将写入处理器、标签的位置写入spring.handlers、spring.schemas中

示例:

spring.handlers

代码语言:javascript
复制
http\://lybgeek.github.com/schema/spi=com.github.lybgeek.spring.schema.SpiNamespaceHandler

spring.schemas

代码语言:javascript
复制
http\://lybgeek.github.com/schema/spi/spi.xsd=META-INF/spi/spi.xsd

注: spring.handlers、spring.schemas需放置在resource/META-INF目录底下

03

示例演示

01

配置xml

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:spi="http://lybgeek.github.com/schema/spi"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
       http://lybgeek.github.com/schema/spi http://lybgeek.github.com/schema/spi/spi.xsd">

    <spi:scan basePackages="com.github.lybgeek"></spi:scan>

02

在启动类上导入xml

代码语言:javascript
复制
@SpringBootApplication
@ImportResource(locations = "classpath:/spi.xml")
public class SpiTestXmlApplication {


    public static void main(String[] args) throws Exception{
        SpringApplication.run(SpiTestXmlApplication.class);
    }


}

03

验证SPI是否注入spring容器

代码语言:javascript
复制
@Override
    public void run(ApplicationArguments args) throws Exception {

        applicationContext.getBeansOfType(SpringSqlDialect.class)
                .forEach((beanName,bean) -> System.out.println(beanName + "-->" + bean));
    }
代码语言:javascript
复制
springMysqlDialect-->com.github.lybgeek.dialect.mysql.SpringMysqlDialect@73041b7d
mysql-hello-->com.github.lybgeek.dialect.mysql.SpringMysqlDialect@574059d5
springOracleDialect-->com.github.lybgeek.dialect.oracle.SpringOracleDialect@4a50d04a

说明已经导入到spring容器中

04

总结

自从spring3+开始引入注解驱动后,在新项目基本上很少会使用xml,但如果是一些老旧的项目,大家如果想实现自定义标签注入到spring,就可以使用本文的方式。

套路就是如下

  •   1、自定义xsd
  •   2、自定义解析BeanDefinitionParser解析器
  •   3、定义NamespaceHandler实现类处理自定义标签的处理器
  •   4、将写入处理器、标签的位置写入spring.handlers、spring.schemas中

本文的实现也是相对简单,如果想深入使用,推荐看看dubbo自定义spring标签

05

demo链接

https://github.com/lyb-geek/springboot-learning/tree/master/springboot-spi-enhance/springboot-spi-framework-spring

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-11-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Linyb极客之路 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档