关于自定义注解的方法,以下是自己的看法,有问题欢迎指出,意在帮助自己日后查看,以下只写了实现过程,没有对其做解释和理解。
第一,引入需要的jar,pom配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
第二,编写注解接口
package com.example.springboottest1.annotations;
import java.lang.annotation.*;
/**
* @author Administrator
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Permission {
String value() default "";
}
第三,利用切面处理注解接口
package com.example.springboottest1.Aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class PermissionAspect {
public static final Logger logger = LoggerFactory.getLogger(PermissionAspect.class);
//注解接口所在包的位置
@Pointcut("@annotation(com.example.springboottest1.annotations.Permission)")
public void annotationPointcut() {
}
@Before("annotationPointcut()")
public void beforePointcut(JoinPoint joinPoint) {
// 此处进入到方法前 可以实现一些业务逻辑
}
@Around("annotationPointcut()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
boolean hasToken = false;
//这里可以写自己的一些判断方法,然后写一些具体的逻辑
if (!hasToken){
String mes = "The token parameter is not included in the requested parameter, the parameter is not valid.";
logger.info(mes);
}
return joinPoint.proceed();
}
/**
* 在切入点return内容之后切入内容(可以用来对处理返回值做一些加工处理)
* @param joinPoint
*/
@AfterReturning("annotationPointcut()")
public void doAfterReturning(JoinPoint joinPoint) {
}
}
第四,测试注解是否生效,写个测试类试一下
package com.example.springboottest1.controller;
import com.example.springboottest1.annotations.Permission;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Administrator
*/
@RestController
public class HelloWord {
@Permission
@RequestMapping("/hello")
public String getHello(){
return "hello world";
}
}
第五,启动项目验证注解是否生效,控制台能打印出那一行日志,代表着就生效了