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

相关推荐
桦说编程4 小时前
记一次 Coding Agent 改动带来的bug与启示
后端·agent·vibecoding
302wanger4 小时前
Mole-在终端里给Mac做减法
后端
一心只读圣贤书4 小时前
本地后端环境与前端联调总结(前端小白视角)
后端
杨利杰YJlio5 小时前
KB5121003更新详解:安全启动证书、AI组件、资源管理器与安装验证
前端·javascript·后端
忙碌碌粒粒橙5 小时前
《用户付一次钱,你的系统为什么处理了两遍:Webhook 重复投递避坑指南》
后端
数字化探索者笔记5 小时前
从零搭建:VMware 银河麒麟V10部署 OceanBase 4.2.5 企业版集中式数据库
后端
西门老铁5 小时前
JWT 是什么?三段式结构、签名原理与 6 个安全坑一次讲透
后端·面试
Codelinghu5 小时前
DeepSeek Harness 出来了,干硬件的我琢磨了一下它到底能干啥
后端
eralong5 小时前
Java 面向对象:继承、多态、接口
java·后端
苏三说技术6 小时前
DeepSeek Harness必装的10个插件
后端