Java implementation of facet oriented based on custom annotation

Purpose: to add an annotation anywhere you want to cut, and then you can realize the aspect oriented programming

Custom annotation class

@Target({ElementType.PARAMETER, ElementType.METHOD})    
@Retention(RetentionPolicy.RUNTIME)  
public @interface LongOu {
    
}

@Target and @ Retention are java meta annotations (4 in total):

@Target: set the usage range of annotation, which can be used in parameters and methods.

@Retention: sets the lifecycle of the annotation, which is set at runtime.

 

Section class:

@Aspect//Declare that this is a facet
@Component//Give this class to spring Administration
public class LogOuAspect {
    // Put the connection point of the section on our annotation
    @Pointcut("@annotation(com.example.demo.log.LongOu)")
    public void ouAspect() {
    }
    // Define the front cut here
    @Before("ouAspect()")
    public void beforeMethod(JoinPoint joinPoint) {
        
        // Perform the action of saving the log here
        System.out.println("Before method.......");
        //Get the parameters of the cut method
        System.out.println(joinPoint.getArgs()[0]);
    }
}

 

Connector class:

@RestController  //springboot Note: the data type returned by all methods under the class is jason
public class AspectController {
    @RequestMapping("/getUser")
    @LongOu//This is our custom annotation. After adding this annotation, you can cut to this method.
    public User getUser(@PathVariable Integer id,HttpServletRequest request) {
        System.out.println("In the method.....");
        User user=new User();
        user.setName("Xiao Ming");
        user.setPassword("xxxx");
        return user;
    }
}

 

Entity class:

public class User {
    Integer id;
    String name;
    String password;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    
    
}

 

Operation result:

Before the method
In the method.....

Tags: Java Programming Spring SpringBoot

Posted on Sat, 02 May 2020 04:52:03 -0700 by rosenrosen