use*_*176 7 java aspectj spring-aop
我在pom.xml中添加了以下依赖项
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.5</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
并在appContext.xml中启用AspectJ,如下所示:
并定义方面如下:
@Component
@Aspect
public class AuthenticationServiceAspect {
@Before("execution(* com.service.impl.AuthenticationServiceImpl.*(..))")
public void adviceMethod(JoinPoint joinPoint) {
if(true){
throw new Exception();
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想禁用这个AOP,以便上面的代码不会被执行?我怎样才能做到这一点?
小智 16
您可以使用带有ConditionalOnExpression批注的属性的启用/禁用组件.当组件被禁用时,方面也是如此.
@Component
@Aspect
@ConditionalOnExpression("${authentication.service.enabled:true}")// enabled by default
public class AuthenticationServiceAspect {
@Before("execution(* com.service.impl.AuthenticationServiceImpl.*(..))")
public void adviceMethod(JoinPoint joinPoint) {
if(true){
throw new Exception();
}
}
}
Run Code Online (Sandbox Code Playgroud)
要禁用方面,只需将authentication.service.enabled = false添加到application.properties即可.
she*_*tem -1
总是有 if() 切入点表达式允许您定义要由建议检查的条件: https://www.eclipse.org/aspectj/doc/next/adk15notebook/ataspectj-pcadvice.html#d0e3697
而且......你的方面已经是一个Spring @Component。为什么不直接通过 @Value 注入属性并决定是否应该执行您的建议?您可以通过上述 if() 切入点或仅检查建议中的值并因此执行或跳过来执行此操作。
@Component
@Aspect
public class AuthenticationServiceAspect {
@Value("${aspect.active}")
private boolean active = true;
@Pointcut("execution(* com.service.impl.AuthenticationServiceImpl.*(..)) && if()")
public static boolean conditionalPointcut() {
return active;
}
@Before("conditionalPointcut()")
public void adviceMethod(JoinPoint joinPoint) {
if(true){
throw new Exception();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10061 次 |
| 最近记录: |