How do I accomplish an aspect in Spring without xml?

How to start an aspect in Java.

How to accomplish aspect in Spring using annotations without XML file?

Many other guides that use xml file to validate configuration.

+3


source to share


2 answers


Define 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 parameter 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 a class of aspects;

@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=");
    }
}

      

+2


source


Use annotations in your class: @Component @Aspect



-1


source







All Articles