注解(Annotation),也叫元数据。一种代码级别的说明。它是JDK1.5及以后版本引入的一个特性,与类、接口、枚举是在同一个层次。它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,用来对这些元素进行说明,注释。 作用分类: ①编写文档:通过代码里标识的元数据生成文档【生成文档doc文档】 ② 代码分析:通过代码里标识的元数据对代码进行分析【使用反射】 ③编译检查:通过代码里标识的元数据让编译器能够实现基本的编译检查【Override】 语法:
@Target({ElementType.METHOD}) //作用目标(常用) @Retention(RetentionPolicy.RUNTIME) //保留(常用) @Inherited //允许子类继承,可以不加 @Documented //注解应该被 javadoc工具记录,可以不加 public @interface ChineseName { public String value();}eg:
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 用户日志 */ @Target({ElementType.METHOD,ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface LogUserAspect { //操作日志类型的描述 public String Operator() default ""; //操作日志类型 public OperatorType OperatorType(); //ID public String Id() default ""; }作用目标(作用范围)解释: ElementType.CONSTRUCTOR 构造方法声明 ElementType.FIELD 字段声明 ElementType.LOCAL_VARIABLE 局部变量申明 ElementType.METHOD 方法声明 ElementType.PACKAGE 包声明 ElementType.PARAMETER 参数声明 ElementType.TYPE 类接口 保留(作用时机) RetentionPolicy.SOURCE 只在源码显示,编译时会丢弃 RetentionPolicy.CLASS 编译时会记录到class中,运行时忽 RetentionPolicy.RUNTIME 运行时存在,可以通过发射读取 用法一: 标记位置:
/** * 新增用户 */ @Override @Transactional @LogUserAspect(Operator="用户新增",Id="#user.id", OperatorType = OperatorType.INSERT) @CacheEvict(cacheNames="UserAllCache",allEntries=true) public int insertUser(User user) { if(user.getEnabled()==null) user.setEnabled(Boolean.TRUE); if(user.getExpired()==null) user.setExpired(Boolean.FALSE); if(user.getIsAdmin()==null) user.setIsAdmin(Boolean.FALSE); if(user.getLocked()==null) user.setLocked(Boolean.FALSE); PasswordHelper.encryptPassword(user); return userMapper.insertSelective(user); }面向切面编程方式,拦截注解并进行业务处理:
@Aspect @Component public class LogAspectAop { private static Logger logger = LoggerFactory.getLogger(LogAspectAop.class); @Pointcut("@annotation(com.cpicauto.framework.aop.LogUserAspect)") public void user_log() { logger.info("进入用户日志操作记录切入点"); } /** * 用户信息拦截 * * @param joinPoint * @throws Throwable */ @Around("user_log()") @Transactional public Object executeUserLog(final ProceedingJoinPoint joinPoint) throws Throwable { String value = "Do something!!!"; Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();//获取方法对象 LogUserAspect logUserAspect = method.getAnnotation(LogUserAspect.class);//获取注解对象 OperatorType operatorType = logUserAspect.OperatorType();//通过注解对象获取其属性值 String id = logUserAspect.Id(); String operator = logUserAspect.Operator(); return value; } }用法二: 在**实体类中属性上,加上一个注解,通过反射获取注解对象,即可获取注解中值进行处理。
public void testName() throws Exception { Person person = new Person(); Class clazz = person.getClass(); Field field = clazz.getDeclaredField("name"); LogUserAspect annotation = field.getAnnotation(ChineseName.class); System.out.println(annotation.OperatorType()); }用法三: 稍高端用法: 使用位置: 至于具体怎么用的,由于涉及到的知识点太多,就不详细讲解了。