I have added following dependency in 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>
And enable AspectJ in appContext.xml as follows:
And define aspect as follows:
@Component
@Aspect
public class AuthenticationServiceAspect {
@Before("execution(* com.service.impl.AuthenticationServiceImpl.*(..))")
public void adviceMethod(JoinPoint joinPoint) {
if(true){
throw new Exception();
}
}
Now I want to disable this AOP so that above code won't get execute? How can I do this?
By placing <aop:aspectj-autoproxy> in your Spring configuration, you can move your pointcut and advice declaration into your Java code using @AspectJ annotations such as @Aspect, @Pointcut, @Before, and @After.
An aspect can be created in spring boot with help of annotations @Aspect annotation and registering with bean container with @Component annotation. Inside the aspect class, we can create advices as required. For example, below class applies around advice on methods inside all classes in package com.
Spring Boot Starter AOP is a dependency that provides Spring AOP and AspectJ. Where AOP provides basic AOP capabilities while the AspectJ provides a complete AOP framework. In the next section, we will implement the different advices in the application.
You may use enabling/disabling component with properties with ConditionalOnExpression annotation. When component is disabled the aspect is too.
@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();
}
}
}
To disabling the aspect, just add authentication.service.enabled=false to your application.properties.
It appears Spring does not support AspectJ's if()
pointcut primitive.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'foo': Initialization of bean failed; nested exception is org.aspectj.weaver.tools.UnsupportedPointcutPrimitiveException: Pointcut expression 'execution(* doSomething(..)) && if()' contains unsupported pointcut primitive 'if'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With