黑马程序员技术交流社区
标题:
【上海校区】java基础之-自定义注解二
[打印本页]
作者:
不二晨
时间:
2018-11-19 17:07
标题:
【上海校区】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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
这里继续使用上一篇的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 "这是一个测试";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
新增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());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
这样使用@ShowMessage时只需要再相应的方法前加上注解就可以了,对了忘记测试下。这里使用postmain测试:
看到返回了来看看日志:
这样就实现了自定义注解的功能,我个人比较喜欢使用Aspectj 处理自定义注解这种方式。定义完成后使用比较方便,那用再哪里加注解就ok。这里提到了AspectJ 稍后我想把 AspectJ也拉出来学习学习也会同时分享下。
---------------------
【转载】
作者:goodLuck@
原文:
https://blog.csdn.net/weixin_43545983/article/details/84073338
作者:
老鸟
时间:
2018-11-20 16:23
作者:
小影姐姐
时间:
2018-11-21 16:32
作者:
不二晨
时间:
2018-11-21 16:55
作者:
魔都黑马少年梦
时间:
2018-11-22 16:51
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2