java基础之-自定义注解二

接上一篇使用Spring AOP 的Aspectj 解析自定义注解,再解析之前需要先做一些准备工作,要使用aspectj就必须启动Spring.我这里使用Spring boot练习。依赖如下:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>
<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.12</version>
	<scope>test</scope>
</dependency>

这里继续使用上一篇的ShowMessage注解 和AnnotationUtile类。
新增Spring boot 控制层 ServiceController类:

package com.annotation.controller;

import com.annotation.impl.AnnotationUtile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ServiceController {
    @Autowired
    private AnnotationUtile annotationUtile;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String showMessage(){
        annotationUtile.test();
        return "这是一个测试";
    }
}

新增aspectJ定义:

package com.annotation.aspect;

import com.annotation.annotation.ShowMessage;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * @Aspect 注解告诉Spring 该类是一个aspect
 */
@Aspect
@Component
public class ShowMessageAspect {

    /**
     * @Before 前置通知表示再方法执行之前执行
     * 这个aspect 的概念这里不做过多描述。 @annotation是 aspect 表达式。
     * @param showMessage
     */
    @Before("@annotation(showMessage)")
    public void before(ShowMessage showMessage){
        System.out.println(showMessage.value());
    }
}

这样使用@ShowMessage时只需要再相应的方法前加上注解就可以了,对了忘记测试下。这里使用postmain测试:
image.png
看到返回了来看看日志:
image.png
这样就实现了自定义注解的功能,我个人比较喜欢使用Aspectj 处理自定义注解这种方式。定义完成后使用比较方便,那用再哪里加注解就ok。这里提到了AspectJ 稍后我想把 AspectJ也拉出来学习学习也会同时分享下。

猜你喜欢

转载自blog.csdn.net/weixin_43545983/article/details/84073338
今日推荐