SpringBoot入门十八,自定义注解的简单实现
                                            项目基本配置参考文章SpringBoot入门一,使用myEclipse新建一个SpringBoot项目,使用myEclipse新建一个SpringBoot项目即可,此示例springboot升级为2.2.1版本。
广昌ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联公司的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:028-86922220(备注:SSL证书合作)期待与您的合作!
1. pom.xml添加aop支持
        org.springframework.boot 
        spring-boot-starter-aop 
 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;
/**
 * 描述:通过@Aspect注解使该类成为切面类
 */
@Aspect
@Component
public class LoginAnnoImpl {
    @Pointcut("@annotation(com.qfx.common.annotation.LoginAnno)")
    private void cut() {
    }
    /**
     * 功能:前置通知
     */
    @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;
    }
}.jpg)
4. 完整项目结构
.jpg)
网站名称:SpringBoot入门十八,自定义注解的简单实现
文章URL:http://www.scyingshan.cn/article/pgdhoj.html

 建站
建站
 咨询
咨询 售后
售后
 建站咨询
建站咨询 
 