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

相关推荐
我的ID配享太庙呀22 分钟前
Django 科普介绍:从入门到了解其核心魅力
数据库·后端·python·mysql·django·sqlite
java叶新东老师1 小时前
goland编写go语言导入自定义包出现: package xxx is not in GOROOT (/xxx/xxx) 的解决方案
开发语言·后端·golang
码事漫谈3 小时前
C++模板元编程从入门到精通
后端
_風箏3 小时前
Java【代码 14】一个用于判断磁盘空间和分区表是否需要清理的工具类
后端
_風箏3 小时前
Java【代码 13】前端动态添加一条记后端使用JDK1.8实现map对象根据key的部分值进行分组(将map对象封装成指定entity对象)
后端
_風箏3 小时前
Java【代码 12】判断一个集合是否包含另一个集合中的一个或多个元素 retainAll() 及其他方法
后端
Java中文社群3 小时前
Coze开源版?别吹了!
人工智能·后端·开源
懂得节能嘛.3 小时前
【SpringAI实战】ChatPDF实现RAG知识库
java·后端·spring
站大爷IP3 小时前
Python爬虫库性能与选型实战指南:从需求到落地的全链路解析
后端
小杰来搬砖3 小时前
在 Java 的 MyBatis 框架中,# 和 $ 的区别
后端