Spring自定义注解扫描的实现

Posted 沁园下的一缕残云

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring自定义注解扫描的实现相关的知识,希望对你有一定的参考价值。

 目标:实现自定义spring自动扫描注解。主要为后期实现分布式服务框架自动注解提供技术支持

  技术分析:通过配置组件扫描标签使spring解析标签。

 1. JewelScanBeanDefaultParser.java

public class JewelScanBeanDefaultParser implements BeanDefinitionParser {

    private static final String RESOURCE_PATTERN = "/**/*.class";

    private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

    public BeanDefinition parse(Element element, ParserContext parserContext) {
        String basePackage = element.getAttribute("base-package");
        if (StringUtils.hasText(basePackage)) {
            try {
                String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(basePackage)
                        + RESOURCE_PATTERN;
                Resource[] resources = resourcePatternResolver.getResources(pattern);
                MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
                for (Resource resource : resources) {
                    if (resource.isReadable()) {
                        MetadataReader reader = readerFactory.getMetadataReader(resource);
                        String className = reader.getClassMetadata().getClassName();
                        Class<?> clazz = Class.forName(className);
                        JewelService jewelService = clazz.getAnnotation(JewelService.class);
                        if (null != jewelService) {
                            AnnotationBeanDefinitionLoader.load(jewelService, clazz, parserContext);
                        }
                        JewelRemote jewelRemote = clazz.getAnnotation(JewelRemote.class);
                        if (null != jewelRemote) {
                            AnnotationBeanDefinitionLoader.load(jewelRemote, clazz, parserContext);
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return null;
    }

}

2. 注解接口定义

JewelRemote.java

@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface JewelRemote {

	public String name() default "";

	public String version() default "v_0.0.1";

	public String registry() default "registry";

}

JewelService.java

@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface JewelService {

	public String name() default "";

	public String version() default "v_0.0.1";

	public String registry() default "registry";
	
	
}

 

以上是关于Spring自定义注解扫描的实现的主要内容,如果未能解决你的问题,请参考以下文章

关于手写实现Spring注解实现自定义配置功能

关于手写实现Spring注解实现自定义配置功能

spring扫描自定义注解并进行操作

自定义SpringBoot Starter 通过注解启动装配

@Service注解无法被扫描到的问题

使用Spring Aop自定义注解实现自动记录日志