java注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。
注解不会也不能影响代码的实际逻辑,仅仅起到辅助性的作用。包含在 java.lang.annotation 包中。
1:写元注解,包括:@Retention,@Target,@Document,@Inherited四种。
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface xxxAnnotation{
/**
* @return whether query cache, true is query cache, false is not.
*/
boolean value() default true;
/**
* @return the expire time of cache, default is 60s
*/
int expireTime() default 60;
}
1.1:@Target:定义注解的作用目标
@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) ///包
1.2:@Retention: 定义注解的保留策略
@Retention(RetentionPolicy.SOURCE) //注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
1.3:@Inherited:说明子类可以继承父类中的该注解
1.4:@Documented:注解表明这个注解应该被 javadoc工具记录. 默认情况下,javadoc是不包括注解的. 但如果声明注解时指定了 @Documented,则它会被 javadoc 之类的工具处理, 所以注解类型信息也会被包括在生成的文档中
切面:AOPxml
<bean id="xxxAspect" class="com.xxx.xxxAspect"/>
<aop:config>
<aop:aspect ref="xxxAspect">
<aop:pointcut id="xxxService" expression="execution(* com.xxx..*.*(..))"/>
<aop:around method="queryxxx"(切面走的方法) pointcut-ref="xxxService"/>
</aop:aspect>
</aop:config>
public class xxxAspect {
public Object queryxxx(ProceedingJoinPoint joinpoint) throws Throwable {
xxxAnnotation clazzCacheSwitcher = joinpoint.getTarget().getClass().getAnnotation(xxxAnnotation.class);
MethodSignature methodSignature = (MethodSignature) joinpoint.getSignature();
xxxAnnotation methodCacheSwitcher = methodSignature.getMethod().getAnnotation(xxxAnnotation.class);
//xxxk可以用于走注解的配置
//下面是用于走调用注解,原来的方法。就是直接注解的入口方法。
joinpoint.proceed();
//xxx执行对应代码
}
}
xml:
<bean id="beanId" class="com.xxxInterceptor"/>
<aop:config>
<!--切入点-->
<aop:pointcut id="xxxPoint" expression="execution(* com.dao..*(..))||execution(* com.dao2..*(..))"/>
<!--在该切入点使用自定义拦截器-->
<aop:advisor pointcut-ref="xxxPoint" advice-ref="beanId"/>
</aop:config>
package com.xxx
import com.alibaba.dxp.daoproxy.annotation.Select;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
public class xxxInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
//得到注解
AA aa = invocation.getMethod().getAnnotation(AA.class);
//注解
Select select = invocation.getMethod().getAnnotation(Select.class);
//xxx业务逻辑
}
}