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;/** * <h6>描述:通过@Aspect注解使该类成为切面类</h6> */@Aspect@Componentpublic class LoginAnnoImpl { @Pointcut("@annotation(com.qfx.common.annotation.LoginAnno)") private void cut() { } /** * <h6>功能:前置通知</h6> */ @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. 完整项目结构
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。