SpringBoot入门十八,自定义注解的简单实现

项目基本配置参考文章SpringBoot入门一,使用myEclipse新建一个SpringBoot项目,使用myEclipse新建一个SpringBoot项目即可,此示例springboot升级为2.2.1版本。

 

1. pom.xml添加aop支持

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

2. 创建自定义注解

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 {

}

元注解释义:
java.lang.annotation提供了四种元注解,专门注解其他的注解(在自定义注解的时候,需要使用到元注解):
@Documented –注解是否将包含在JavaDoc中
@Retention –什么时候使用该注解
@Target –注解用于什么地方
@Inherited – 是否允许子类继承该注解

 

3. 创建自定义注解解析

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("自定义注解生效了");
    }
}

至此自定义注解就编写完毕了,下面来看看调用

4. 使用自定义注解

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入门十八,自定义注解的简单实现

4. 完整项目结构

SpringBoot入门十八,自定义注解的简单实现

猜你喜欢

转载自blog.51cto.com/1197822/2449700