自定义注解,与spring框架中自带的注解如 @Controller 等,用法一直,接下来自定义一个注解
1 引入pom
2 新建一个注解
3 配置注解切面
4 使用
1 引入pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2 新建一个名字为ParamCheck的自定义注解
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ParamCheck {
}
3 配置该注解的切面
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.aspectj.lang.JoinPoint;
import java.lang.reflect.Method;
@Aspect
@Component
public class ParamCheckAop implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Pointcut("@annotation(com.example.test.config.ParamCheck)")
public void checkPoint() {
}
@Before(value = "checkPoint()")
public void before(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
System.out.println(method);
Object[] args = joinPoint.getArgs();
String[] parameterNames = new DefaultParameterNameDiscoverer().getParameterNames(method);
// 这里仅仅是打印,既然获取到了,那么如何校验,或者其他处理都可以
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
System.out.println(parameterNames[i]);
}
}
}
4 使用方法,直接在一个方法上加入该注解,那么他就会获取到name 的值,然后进行相应操作
@Service
public class AreaServiceImpl implements AreaService {
@ParamCheck
@Override
public void kajf(String name) {
System.out.println(name);
}
}