项目基本配置参考文章SpringBoot入门一,使用myEclipse新建一个SpringBoot项目,使用myEclipse新建一个SpringBoot项目便可,此示例springboot升级为2.2.1版本。java
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 – 是否容许子类继承该注解web
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. 完整项目结构