这是我参与更文挑战的第30天,活动详情查看: 更文挑战
注解定义
注解(annotation),是源代码的元数据,代码的标签
本质一,是一个附属品,依赖其他元素存在
本质二,本身没有任何作用,恰当时候由外部程序解析产生作用
作用:
简化配置
增加代码可读性
提高系统可维护性
分类
按运行机制
SOURCE源码注解:只在源码中存在,编译成class不存在
CLASS编译时注解:源码和class文件都存在,运行时移除 (@Override,@Deprecated,。。)
RUNTIME运行时注解:保留到运行时,(@Autowired)
按来源
内置注解
第三方注解
自定义注解
元注解(注解的注解) Retention 注解生命周期 Documented 文档化注解,被javadoc工具文档化 Inherited 注解是自动继承的,想让一个类和他的子类都包含某个注解,使用 Target Target通过ElementType来指定注解可使用范围
Springboot实现自定义注解
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
写一个注解
import java.lang.annotation.*;
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation {
String name() default "";
int age() default 0;
}
实现
import org.springframework.stereotype.Component;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
@Component
@Aspect
public class AspectImpl {
@Pointcut("@annotation(com.i18n.config.MyAnnotation)")
private void cut(){}
// 开始环绕
@Around("cut()")public void around(ProceedingJoinPoint joinPoint)throws Throwable{
System.out.println("1");
try{joinPoint.proceed();}
catch (Exception e){
e.printStackTrace();
}System.out.println("4");
}
@Before("cut()")public void before(){System.out.println("2");
}
@After("cut()")public void after(){System.out.println("5");
}
}
使用
import com.i18n.config.MyAnnotation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class AnnotationCtrl {
@RequestMapping("/do")
@MyAnnotation
public void test(){
System.out.println(3);
}
}