Springs Java Aspectj注解实现从0到1

483 阅读1分钟

pom.xml导入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

编写注解接口

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckPermission {
}

编写注解实现,并将实现与注解进行绑定

@Slf4j
@Component
public class AnnChecker {
    @Before("@annotation(com.xiaohongshu.data.events.controller.CheckPermission)")
    public void checkClusterPermission(JoinPoint joinPoint) {
		System.out.println("hello, world");
    }
}

调用注解

在Controller API中调用

    /* 内部测试接口 */
    @RequestMapping(value = "//ping", method = RequestMethod.GET)
    @ResponseBody
    @CheckPermission
    public Result rbacPing() {
        return Result.success("pong");
    }

在其他方法中调用

引入注解

    @CheckPermission
    public void CheckPermission1(UserInfo userInfo, int taskID, Op op) {
        ;
    }

调用注解方法的类必须被Spring托管才能在调用时触发注解

    @Autowired
    UserController self;
    /* ... other code ... */
    self.CheckPermission1(user, 1, Op.UPDATE);