icp备案网站快速备案专家,深圳保障房申请条件2022,做网站公司费用,在线教育网站开发经验简历填写背景 #xff1a; 需求 需要获取某个包下的所有的注解 并不是全部项目的 所以 只用针对某个包 进行扫描 获取注解 数据就行
百度了一圈 spring boot 没有自带的 获取注解集合的方法
在看 php 中 hyperf 框架 看到了 这个方法 就是因为 我需求是 php 和java 合体 微服务开发 …背景 需求 需要获取某个包下的所有的注解 并不是全部项目的 所以 只用针对某个包 进行扫描 获取注解 数据就行
百度了一圈 spring boot 没有自带的 获取注解集合的方法
在看 php 中 hyperf 框架 看到了 这个方法 就是因为 我需求是 php 和java 合体 微服务开发 百度了一圈 好像 spring boot 没有提供这种方法 本来打算写一个 突然发现了一个很好用的依赖包 解决了 我的问题
dependencygroupIdorg.reflections/groupIdartifactIdreflections/artifactIdversion0.10.2/version/dependency这个reflections 包 主要作用是
这个依赖是用于 Java 项目中的反射操作的。org.reflections 是一个 Java 库允许你在运行时查找和使用类、方法、字段等。它提供了一种简单的方式来扫描你的项目或者外部库中的类和注解从而帮助你进行一些动态的操作比如查找特定的类、方法或者注解或者执行特定的操作。
详细用法 自行百度 我的需求 做法 代码如下
package com.init.utils;import com.api.exception.KuaiJingRuntimeException;import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.util.ClasspathHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;import org.reflections.util.ConfigurationBuilder;
import org.springframework.web.bind.annotation.RequestMapping;import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;/*** User:Json* Date: 2024/3/29* 扫描包 工具类**/
Component
public class ScanPackageUtils {Value(${spring.application.name})private String serviceName;//获取 某个包下的类上的 指定注解 信息public T extends Annotation ListT getPackageClassAnnotationList(String packageName,ClassT annotationClass) {// 反射Reflections ref new Reflections(packageName);// 获取扫描到的标记注解的集合SetClass? set ref.getTypesAnnotatedWith((Class? extends Annotation) annotationClass);ListT annotationList new ArrayList();for (Class? c : set) {// 循环获取标记的注解T annotation (T) c.getAnnotation(annotationClass);annotationList.add(annotation);}return annotationList;}//获取 某个包下所有类下的 方法上的 指定注解 信息public T extends Annotation ListT getPackageMethodAnnotationList(String packageName,ClassT annotationClass) {Reflections reflections new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(packageName)).setScanners(new MethodAnnotationsScanner()));SetMethod methods reflections.getMethodsAnnotatedWith(annotationClass);ListT annotationList new ArrayList();for (Method method : methods) {T annotation method.getAnnotation(annotationClass);if (annotation ! null) {annotationList.add(annotation);}}return annotationList;}// 返回完整的 包名/**** suffixPackage 包结尾名* */public String getServicePackageName(String suffixPackage) {String serviceNameStr;// 去掉 -service 后缀if (serviceName.endsWith(-service)) {serviceNameStr serviceName.substring(0, serviceName.lastIndexOf(-service));}if(StringUtils.isEmpty(serviceNameStr)){throw new KuaiJingRuntimeException(配置文件中 服务名称格式不正确);}return com.xxx.serviceNameStr.suffixPackage;}
}
嘎嘎好用