一、java注解简介
-
java注解(Annotation)
java注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能
2.1 JDK基本注解(类似于英文单词)
2.2 JDK元注解 (类似于英文字母)
2.3 自定义注解
- JDK基本注解
3.1 重写:@Override
3.2 压制编辑器警告:@SuppressWarnings(value=“unchecked”)
二、java元注解(重点)
作用:元注解用于修饰其他注解
- @Retention:定义注解的保留策略
@Retention(RetentionPolicy.SOURCE)//注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS)//默认的保留政策,注解会在class字节码文件中存在,但运行时无法获得
@Retention(RetentionPolicy.RUNTIME)//注解会在class字节码文件中存在,在运行时可以通过反射获取到
- @Target:指定被修饰的Annotation可以放置的位置(被修饰的目标)
@Target(ElementType.TYPE) //接口、类
@Target(ElementType.FIELD) //属性
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法参数 @Target(ElementType.CONSTRUCTOR) //构造函数
@Target(ElementType.LOCAL_VARIABLE) //局部变量
@Target(ElementType.ANNOTATION_TYPE) //注解
@Target(ElementType.PACKAGE) //包
注:可以指定多个位置,例如:@Target({ElementType.METHOD,ElementType.TYPE}),也就是次注解可以在方法和类上面使用。
-
@inherited:指定被修饰的Annotation将具有继承性
-
@Documented:指定被修饰的该Annotation可以被javadoc工具提取成文档.
package com.xfz.ssm.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author xfz
* @site www.xfz.com
* @company zking
* @create 2019-12-25 18:32
*/
//可以在编译器生效,运行项目时会在class文件中自动消失
//@Retention(RetentionPolicy.SOURCE)
//在运行中通过反射获取到
//@Retention(RetentionPolicy.RUNTIME)
//存在class字节码文件中,但运行时无法获取到
@Retention(RetentionPolicy.CLASS)
//demo注解只能加在类上
//@Target(ElementType.TYPE)
//注解可以加在属性上
//@Target(ElementType.FIELD)
//注解可以加在方法上
@Target(ElementType.METHOD)
public @interface Demo {
}
三、自定义注解
注解分类(根据Annotation 是否包含成员变量,可以把Annotation分为两类)
-
标记Annotation:
没有成员变量的Annotation,这种Annotation仅利用自身的存在与否来提供信息 -
元数据Annotation:
办函成员变量的Annotation,他们可以接受(和提供)更多的元数据
案例一(获取类与方法上的注解值):
TranscationModel
package com.xfz.ssm.annotation.p1;
/**
* @author xfz
* @site www.xfz.com
* @company zking
* @create 2019-12-25 18:32
*/
public enum TranscationModel {
Read, Write, ReadWrite
}
MyAnnotation1
package com.xfz.ssm.annotation.p1;
import java.lang.annotation.*;
/**
* @author xfz
* @site www.xfz.com
* @company zking
* @create 2019-12-25 18:32
*
* MyAnnotation1注解可以用在类、接口、属性、方法上
* 注解运行期也保留
* 不可继承
*/
@Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation1 {
String name();
}
MyAnnotation2
package com.xfz.ssm.annotation.p1;
import java.lang.annotation.*;
/**
* @author xfz
* @site www.xfz.com
* @company zking
* @create 2019-12-25 18:32
*
* MyAnnotation2注解可以用在方法上
* 注解运行期也保留
* 不可继承
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation2 {
TranscationModel model() default TranscationModel.ReadWrite;
}
MyAnnotation3
package com.xfz.ssm.annotation.p1;
import java.lang.annotation.*;
/**
* @author xfz
* @site www.xfz.com
* @company zking
* @create 2019-12-25 18:32
*
* MyAnnotation3注解可以用在方法上
* 注解运行期也保留
* 可继承
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyAnnotation3 {
TranscationModel[] models() default TranscationModel.ReadWrite;
}
Demo1
package com.xfz.ssm.annotation.p1;
/**
* @author xfz
* @site www.xfz.com
* @company zking
* @create 2019-12-25 18:32
*
* 获取类与方法上的注解值
*/
@MyAnnotation1(name = "abc")
public class Demo1 {
@MyAnnotation1(name = "xyz")
private Integer age;
@MyAnnotation2(model = TranscationModel.Read)
public void list() {
System.out.println("list");
}
@MyAnnotation3(models = {TranscationModel.Read, TranscationModel.Write})
public void edit() {
System.out.println("edit");
}
}
案例二(获取类属性上的注解属性值:
Demo2
package com.xfz.ssm.annotation.p2;
/**
* @author xfz
* @site www.xfz.com
* @company zking
* @create 2019-12-25 18:32
*
* 获取类属性上的注解属性值
*/
public class Demo2 {
@TestAnnotation(value = "这就是value对应的值_msg1", what = "这就是what对应的值_msg1")
private static String msg1;
@TestAnnotation("这就是value对应的值1")
private static String msg2;
@TestAnnotation(value = "这就是value对应的值2")
private static String msg3;
@TestAnnotation(what = "这就是what对应的值")
private static String msg4;
}
TestAnnotation
package com.xfz.ssm.annotation.p2;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author xfz
* @site www.xfz.com
* @company zking
* @create 2019-12-25 18:32
*
*/
//@Retention(RetentionPolicy.SOURCE)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface TestAnnotation {
String value() default "默认value值";
String what() default "这里是默认的what属性对应的值";
}
Demo2Test
package com.xfz.ssm.annotation.p2;
import org.junit.Test;
/**
* @author xfz
* @site www.xfz.com
* @company zking
* @create 2019-12-25 18:32
*
*/
public class Demo2Test {
@Test
public void test1() throws Exception {
TestAnnotation msg1 = Demo2.class.getDeclaredField("msg1").getAnnotation(TestAnnotation.class);
System.out.println(msg1.value());
System.out.println(msg1.what());
}
@Test
public void test2() throws Exception{
TestAnnotation msg2 = Demo2.class.getDeclaredField("msg2").getAnnotation(TestAnnotation.class);
System.out.println(msg2.value());
System.out.println(msg2.what());
}
@Test
public void test3() throws Exception{
TestAnnotation msg3 = Demo2.class.getDeclaredField("msg3").getAnnotation(TestAnnotation.class);
System.out.println(msg3.value());
System.out.println(msg3.what());
}
@Test
public void test4() throws Exception{
TestAnnotation msg4 = Demo2.class.getDeclaredField("msg4").getAnnotation(TestAnnotation.class);
System.out.println(msg4.value());
System.out.println(msg4.what());
}
}
案例三(获取参数修饰注解对应的属性值):
Demo3
package com.xfz.ssm.annotation.p3;
/**
* @author xfz
* @site www.xfz.com
* @company zking
* @create 2019-12-25 18:32
*
*
* 获取参数修饰注解对应的属性值
*/
public class Demo3 {
public void hello1(@IsNotNull(true) String name) {
System.out.println("hello:" + name);
}
public void hello2(@IsNotNull String name) {
System.out.println("hello:" + name);
}
public void hello3(@IsNotNull(true) String name,@IsNotNull String sex,@IsNotNull(true) String addr) {
System.out.println("hello:" + name);
}
}
IsNotNull
package com.xfz.ssm.annotation.p3;
import java.lang.annotation.*;
/**
* @author xfz
* @site www.xfz.com
* @company zking
* @create 2019-12-25 18:32
*
* 非空注解:使用在方法的参数上,false表示此参数可以为空,true不能为空
*/
@Documented
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface IsNotNull {
boolean value() default false;
}
Demo3Test
package com.xfz.ssm.annotation.p3;
import org.junit.Test;
import java.lang.reflect.Parameter;
/**
* @author xfz
* @site www.xfz.com
* @company zking
* @create 2019-12-25 18:32
*
*/
public class Demo3Test {
@Test
public void hello1() throws Exception {
Demo3 demo3 = new Demo3();
for (Parameter parameter : demo3.getClass().getMethod("hello1", String.class).getParameters()) {
IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);
if(annotation != null){
System.out.println(annotation.value());//true
}
}
}
@Test
public void hello2() throws Exception {
Demo3 demo3 = new Demo3();
for (Parameter parameter : demo3.getClass().getMethod("hello2", String.class).getParameters()) {
IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);
if(annotation != null){
System.out.println(annotation.value());//false
}
}
}
@Test
public void hello3() throws Exception {
Demo3 demo3 = new Demo3();
for (Parameter parameter : demo3.getClass().getMethod("hello3", String.class,String.class,String.class).getParameters()) {
IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);
if(annotation != null){
System.out.println(annotation.value());//true false true
}
}
}
}
四、Aop自定义注解的应用(重点)
案例:
MyLog
package com.xfz.ssm.annotation.springAop;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author xfz
* @site www.xfz.com
* @company zking
* @create 2019-12-25 18:32
*
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLog {
String desc();
}
LogController
package com.xfz.ssm.annotation.springAop;
import org.springframework.stereotype.Component;
/**
* @author xfz
* @site www.xfz.com
* @company zking
* @create 2019-12-25 18:32
*
*/
@Component
public class LogController {
@MyLog(desc = "这是结合spring aop知识,讲解自定义注解应用的一个案例")
public void testLogAspect(){
System.out.println("这里随便来点啥");
}
@MyLog(desc = "增加书籍")
public void bookAdd(){
System.out.println("这里随便来点啥");
}
}
MyLogAspect
package com.xfz.ssm.annotation.springAop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* @author xfz
* @site www.xfz.com
* @company zking
* @create 2019-12-25 18:32
*
*/
@Component
@Aspect
public class MyLogAspect {
private static final Logger logger = LoggerFactory.getLogger(MyLogAspect.class);
/**
* 只要用到了com.javaxl.p2.annotation.springAop.MyLog这个注解的,就是目标类
*/
@Pointcut("@annotation(com.xfz.ssm.annotation.springAop.MyLog)")
private void MyValid() {
}
//之前的切换界面的写法
@Around("execution(* *..*Service.*pager(..))")
private void MyValid2() {
}
@Before("MyValid()")
public void before(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
logger.debug("[" + signature.getName() + " : start.....]");
MyLog myLog = signature.getMethod().getAnnotation(MyLog.class);
logger.debug("【目标对象方法被调用时候产生的日志,记录到日志表中】:"+myLog.desc());
}
}
BaseTestCase
package com.xfz.ssm.annotation.springAop;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author xfz
* @site www.xfz.com
* @company zking
* @create 2019-12-25 18:32
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class BaseTestCase {
}
LogControllerTest
package com.xfz.ssm.annotation.springAop;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author xfz
* @site www.xfz.com
* @company zking
* @create 2019-12-25 18:32
*
*/
public class LogControllerTest extends BaseTestCase {
@Autowired
private LogController logController;
@Test
public void testLogAspect(){
//先走前置通知
logController.testLogAspect();
}
}