Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How run aspect in Spring without xml? [closed]

How to run an aspect in Java.

How to run an aspect in Spring using annotations, without xml file?

Many other tutorials using xml file for configuration ascpect.

like image 886
Stack Over Avatar asked May 02 '17 10:05

Stack Over


People also ask

Does Spring boot avoid XML configuration?

Advantages of Spring Boot:It avoids writing lots of boilerplate Code, Annotations and XML Configuration. It is very easy to integrate Spring Boot Application with its Spring Ecosystem like Spring JDBC, Spring ORM, Spring Data, Spring Security etc.

How do I enable aspect in Spring?

To enable @AspectJ, spring AOP provides @EnableAspectJAutoProxy annotation which will be annotated in java configuration. To work with spring AOP and @AspectJ support, we need to create a class annotated with @Aspect annotation.

What is PointCut and JoinPoint in Spring?

JoinPoint: Joinpoint are points in your program execution where flow of execution got changed like Exception catching, Calling other method. PointCut: PointCut are basically those Joinpoints where you can put your advice(or call aspect). So basically PointCuts are the subset of JoinPoints.

Does Spring use AspectJ?

The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default.


1 Answers

Define a custom annotation;

@Target({ElementType.TYPE ,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Loggable {

}

Annotate your method that you want to intercept ;

@Service
public class MyAwesomeService {

    @Loggable
    public void myAwesomemethod(String someParam) throws Exception {
        // do some awesome things.
    }
}

Add aspect dependencies to your pom.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
</dependency>

and define your aspects class ;

@Aspect
@Component
public class LoggingHandler {

     @Before("@annotation(com.example.annotation.Loggable)")
     public void beforeLogging(JoinPoint joinPoint){
         System.out.println("Before running loggingAdvice on method=");

    }

    @After("@annotation(com.example.annotation.Loggable)")
    public void afterLogging(JoinPoint joinPoint){
        System.out.println("After running loggingAdvice on method=");
    }
}
like image 95
Tunceren Avatar answered Oct 02 '22 06:10

Tunceren