目标:实现自定义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"; }
时间: 2024-12-26 17:47:31