SpringBoot entry XVIII custom annotation simple implementation

The basic configuration of the project refer to the article SpringBoot Getting Started, using a SpringBoot myEclipse new project , a new use myEclipse SpringBoot project can be, this example springboot upgraded to version 2.2.1.

 

1. pom.xml add aop support

<!-- 引入aop切面支持 -->
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2. Create a custom annotation

package com.qfx.common.annotation;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Documented
@Retention(RUNTIME)
@Target(METHOD)
public @interface LoginAnno {

}

Meta-annotation Interpretation:
Classes in java.lang.annotation provides four yuan notes, special notes to other notes (in custom annotation when the need to use meta-annotation):
@Documented - whether notes will be included in the JavaDoc
@Retention - What when using the annotation
@Target - notes for what
@Inherited - whether to allow the subclass inherits the comment

 

3. Create a custom parsing comment

package com.qfx.common.annotation;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * <h5>描述:通过@Aspect注解使该类成为切面类</h5>
 */
@Aspect
@Component
public class LoginAnnoImpl {

    @Pointcut("@annotation(com.qfx.common.annotation.LoginAnno)")
    private void cut() {
    }

    /**
     * <h5>功能:前置通知</h5>
     */
    @Before("cut()")
    public void before() {
        System.out.println("自定义注解生效了");
    }
}

Thus custom annotation on the preparation finished, let's look at call

4. Use custom annotations

package com.qfx.common.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.qfx.common.annotation.LoginAnno;

@RestController
@RequestMapping("login")
public class LoginController {

    @RequestMapping("reg")
    public String reg(String userName) {
        return "用户[" + userName +"]注册成功~!";
    }

    @RequestMapping("login")
    @LoginAnno
    public String login(String userName) {
        return "欢迎您:" + userName;
    }
}

SpringBoot entry XVIII custom annotation simple implementation

4. Complete project structure

SpringBoot entry XVIII custom annotation simple implementation

Guess you like

Origin blog.51cto.com/1197822/2449700