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用于匹配标记了指定注解类型的类以及其子类。

相关推荐
Thneonl2 分钟前
服务不通先别抓包:DNS 解析器的坑比内核网络栈多
后端·程序员
Thneonl2 分钟前
一启动就 Exited(137):内存限制背后藏了四个参数
后端·架构
斯维赤9 分钟前
从 @Tool 到 Agent 流水线:LangChain4j 进阶教学,一个库打全套
java·后端
对象存储与RustFS10 分钟前
RustFS 生产部署实战:Docker / 二进制 / K8s Operator 三条路径怎么选
后端
知守观18 分钟前
Spring Boot 2.1.0 停维护5年,10个依赖4个有CVE——2022年老项目的安全体检报告
spring boot·后端
SimonKing21 分钟前
SSE项目`nexus-sse`持续优化,不一样的视觉效果
java·后端·程序员
斑鸠喳喳21 分钟前
读写锁模式 Read-Write Lock
java·后端
Thneonl25 分钟前
etcd 磁盘写满的那 6 分钟:控制面是怎么一步步瘫的
后端·架构
Tim00725 分钟前
deepseek harness 导出公司报表实战
后端
明月_清风30 分钟前
一个完整的数据平台是怎么工作的?从数据源到数据分析
大数据·后端·数据分析