spring自己實現注解,java 掃描自定義注解_利用spring 自定義注解掃描 找出使用自定義注解的類

 2023-10-20 阅读 30 评论 0

摘要:我們常常有掃描項目里帶有指定注解的class, 下面是利用spring掃描自定義注解的方法, 還是比較靈活的我這里將掃描到的class放到map, 你可以放到其他地方,以便后期使用spring自己實現注解。import lombok.extern.slf4j.Slf4j;import org.apache.shiro.SecurityUtils;import org

我們常常有掃描項目里帶有指定注解的class, 下面是利用spring掃描自定義注解的方法, 還是比較靈活的

我這里將掃描到的class放到map, 你可以放到其他地方,以便后期使用

spring自己實現注解。import lombok.extern.slf4j.Slf4j;

import org.apache.shiro.SecurityUtils;

import org.apache.shiro.session.Session;

java自定義注解實現數據校驗,import org.springframework.context.ApplicationEvent;

import org.springframework.context.ApplicationListener;

import org.springframework.core.io.Resource;

spring自定義注解切面、import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import org.springframework.core.io.support.ResourcePatternResolver;

import org.springframework.core.type.classreading.CachingMetadataReaderFactory;

Springboot注解,import org.springframework.core.type.classreading.MetadataReader;

import org.springframework.core.type.classreading.MetadataReaderFactory;

import org.springframework.util.ClassUtils;

java自定義注解。import org.springframework.util.StringUtils;

import javax.persistence.Table;

import java.io.IOException;

import java.util.HashMap;

import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;

/**

* 掃描指定包下帶有指定注解的class

* @author jaffreyen

* @date 2018/3/5

*/

@Slf4j

public class MyApplicationListener implements ApplicationListener {

/**

* Handle an application event.

*

* @param event the event to respond to

*/

@Override

public void onApplicationEvent(ApplicationEvent event) {

ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

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

// 掃描的包名

final String BASE_PACKAGE = "com.xxx";

Map> classCache = new HashMap<>();

try {

String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(BASE_PACKAGE)

+ RESOURCE_PATTERN;

Resource[] resources = resourcePatternResolver.getResources(pattern);

MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

for (Resource resource : resources) {

if (resource.isReadable()) {

MetadataReader reader = readerFactory.getMetadataReader(resource);

//掃描到的class

String className = reader.getClassMetadata().getClassName();

Class> clazz = Class.forName(className);

//判斷是否有指定注解

Table annotation = clazz.getAnnotation(Table.class);

if(annotation != null){

//這個類使用了自定義注解

classCache.put(className, clazz);

}

}

}

} catch (IOException | ClassNotFoundException e) {

log.error("讀取class失敗", e);

}

}

}

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/152241.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息