Spring获取指定包下,添加了指定注解的方法

public void getMethod() throws IOException, ClassNotFoundException {
        ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
        MetadataReaderFactory metaReader = new CachingMetadataReaderFactory(resourceLoader);
        Resource[] resources = resolver.getResources("classpath*:com/moon/**/*.class");

        for (Resource resource : resources) {
            MetadataReader reader = metaReader.getMetadataReader(resource);
            String className = reader.getClassMetadata().getClassName();
            Class<?> cla = Loader.loadClass(className);
            Method[] ms = cla.getMethods();
            for (Method m : ms) {
                PreAuthorize aa = m.getAnnotation(PreAuthorize.class);
                System.out.println(aa);
            }
        }
    }

resolver.getResources(“classpath*:com/moon/**/*.class”)参数是自己指定的包路径

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
获取添加了自定义注解的所有方法,你可以使用 Spring 的反射机制。下面是一个示例代码,演示了如何获取添加指定注解的所有方法: ```java import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.stereotype.Component; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; @Component public class AnnotationMethodProcessor implements BeanPostProcessor { private List<Method> annotatedMethods = new ArrayList<>(); @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { Class<?> clazz = bean.getClass(); Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (AnnotationUtils.findAnnotation(method, YourCustomAnnotation.class) != null) { annotatedMethods.add(method); } } return bean; } public List<Method> getAnnotatedMethods() { return annotatedMethods; } } ``` 在上面的示例代码中,首先,你需要在自定义的注解处理器类(例如上述示例中的 `AnnotationMethodProcessor`)上添加 `@Component` 注解,以便让 Spring 容器自动扫描并进行初始化。然后,你可以在 `postProcessBeforeInitialization` 方法中使用 `AnnotationUtils.findAnnotation` 方法来判断方法是否添加指定的自定义注解,并将这些方法添加到 `annotatedMethods` 列表中。 接下来,你可以在需要获取添加了自定义注解的所有方法的地方使用 `AnnotationMethodProcessor` 类。例如: ```java List<Method> annotatedMethods = annotationMethodProcessor.getAnnotatedMethods(); ``` 这样,`annotatedMethods` 列表中就包含了添加了自定义注解的所有方法的 `Method` 对象。你可以根据需要进一步处理这些方法。请注意,你需要保证 `AnnotationMethodProcessor` 类已经被 Spring 容器正确初始化,才能获取到正确的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值