您的位置:首页 > 编程语言 > Java开发

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

2019-11-12 15:02 1641 查看

项目基本配置参考文章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;
}
}

4. 完整项目结构

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: