method.isAnnotationPresent(Xxx.class)一直为null

method.isAnnotationPresent(Xxx.class)一直为null_第1张图片method.isAnnotationPresent(Xxx.class)一直为null_第2张图片

method.isAnnotationPresent(Xxx.class)一直为null_第3张图片

method.isAnnotationPresent(Xxx.class)一直为null_第4张图片

​​​​package com.dj.springtest.aspect;

import com.dj.springtest.annotation.RequireRoles;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;

/**
 * User: ldj
 * Date: 2023/10/22
 * Time: 4:25
 * Description: No Description
 */
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class PermissionControl {

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void test() {
        Map beans = applicationContext.getBeansWithAnnotation(RestController.class);
        for (Object bean : beans.values()) {
            //反射获取字节码对象
            Class clazz = bean.getClass();
            Method[] methods = clazz.getSuperclass().getDeclaredMethods();
            for (Method method : methods) {
                boolean isPresent = method.isAnnotationPresent(RequireRoles.class);
                log.info("是否存在@RequireRoles注解:{}", isPresent);
                if (isPresent) {
                    RequireRoles annotation = method.getAnnotation(RequireRoles.class);
                    log.info("roles:{}",Arrays.toString(annotation.roles()));
                }
            }
        }
    }

}

你可能感兴趣的:(java,前端,开发语言)