SpringAOP中@within和@annotation以及 @within和@target的区别

@within和@annotation和@target的区别:

1、within与annotation作用级别不同

java 复制代码
 1.  @within 对象级别
 2.  @annotation 方法级别

例如:

@Slf4j 复制代码
@Aspect
@RequiredArgsConstructor
public class SecurityInnerAspect implements Ordered {

	private final HttpServletRequest request;

	@SneakyThrows
	@Around("@within(inner) || @annotation(inner)")
	public Object around(ProceedingJoinPoint point, Inner inner) {
		// 实际注入的inner实体由表达式后一个注解决定,即是方法上的@Inner注解实体,若方法上无@Inner注解,则获取类上的
		if (inner == null) {
			Class<?> clazz = point.getTarget().getClass();
			inner = AnnotationUtils.findAnnotation(clazz, Inner.class);
		}
		String header = request.getHeader(SecurityConstants.FROM);
		if (inner.value() && !StrUtil.equals(SecurityConstants.FROM_IN, header)) {
			log.warn("访问接口 {} 没有权限", point.getSignature().getName());
			throw new AccessDeniedException("Access is denied");
		}
		return point.proceed();
	}

	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE + 1;
	}

}
less 复制代码
//这个用于拦截标注在类上面的@RestController注解
@Around("@within(org.springframework.web.bind.annotation.RestController") 
       
// 这个用于拦截标注在方法上面的@RestController注解
@Around("@annotation(org.springframework.web.bind.annotation.RestController") 
        
@within和@target的区别:

2、within 和 target的作用层级不同

2.1、within

less 复制代码
@target:
使用 @target注解可以匹配被指定注解标记的目标对象。

例如,如果一个类被标记了 @SomeAnnotation,
那么使用 @target(com.example.SomeAnnotation) 就可以匹配到这个类。

代码例子

less 复制代码
@SomeAnnotation 
public class MyService { ... } 
@Before("@target(com.example.SomeAnnotation)") 
public void someAdvice() { ... }

2.2、target

less 复制代码
@within: 
与 @target不同, @within匹配被指定注解标记的目标对象的类以及其所有子类。

比如,如果MyService标记了 @SomeAnnotation,那么所有继承自MyService的类也会被匹配到。

代码例子

less 复制代码
@SomeAnnotation 
public class MyService { ... } 

public class AnotherService extends MyService { ... } 

@Before("@within(com.example.SomeAnnotation)") 
public void someAdvice() { ... }

简而言之, @target 用于匹配指定的注解类型,而 @within用于匹配标记了指定注解类型的类以及其子类。

相关推荐
一 乐6 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
码事漫谈7 小时前
Protocol Buffers 编码原理深度解析
后端
码事漫谈7 小时前
gRPC源码剖析:高性能RPC的实现原理与工程实践
后端
踏浪无痕8 小时前
AI 时代架构师如何有效成长?
人工智能·后端·架构
程序员小假9 小时前
我们来说一下无锁队列 Disruptor 的原理
java·后端
武子康10 小时前
大数据-209 深度理解逻辑回归(Logistic Regression)与梯度下降优化算法
大数据·后端·机器学习
maozexijr10 小时前
Rabbit MQ中@Exchange(durable = “true“) 和 @Queue(durable = “true“) 有什么区别
开发语言·后端·ruby
源码获取_wx:Fegn089510 小时前
基于 vue智慧养老院系统
开发语言·前端·javascript·vue.js·spring boot·后端·课程设计
独断万古他化10 小时前
【Spring 核心: IoC&DI】从原理到注解使用、注入方式全攻略
java·后端·spring·java-ee
毕设源码_郑学姐10 小时前
计算机毕业设计springboot基于HTML5的酒店预订管理系统 基于Spring Boot框架的HTML5酒店预订管理平台设计与实现 HTML5与Spring Boot技术驱动的酒店预订管理系统开
spring boot·后端·课程设计