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

相关推荐
IT_102431 分钟前
Spring Boot项目开发实战销售管理系统——系统设计!
大数据·spring boot·后端
ai小鬼头2 小时前
AIStarter最新版怎么卸载AI项目?一键删除操作指南(附路径设置技巧)
前端·后端·github
Touper.2 小时前
SpringBoot -- 自动配置原理
java·spring boot·后端
一只叫煤球的猫2 小时前
普通程序员,从开发到管理岗,为什么我越升职越痛苦?
前端·后端·全栈
一只鹿鹿鹿2 小时前
信息化项目验收,软件工程评审和检查表单
大数据·人工智能·后端·智慧城市·软件工程
专注VB编程开发20年3 小时前
开机自动后台运行,在Windows服务中托管ASP.NET Core
windows·后端·asp.net
程序员岳焱3 小时前
Java 与 MySQL 性能优化:MySQL全文检索查询优化实践
后端·mysql·性能优化
一只叫煤球的猫3 小时前
手撕@Transactional!别再问事务为什么失效了!Spring-tx源码全面解析!
后端·spring·面试
旷世奇才李先生4 小时前
Ruby 安装使用教程
开发语言·后端·ruby
沃夫上校6 小时前
Feign调Post接口异常:Incomplete output stream
java·后端·微服务