简化代码,提高开发效率

注解分类

一、运行机制划分:

  • 源码注解
  • 编译时注解 (1.内的注解都是)
    只在编译器上起作用
  • 运行时注解
    运行阶段起作用,影响运行逻辑,例如@Autowired

二、按照来源划分:

1.jdk自带注解

@Override 复写父类,接口方法
@Depreted 标记过时
@SuppressWarning(“deprecation”) 忽略警告

2.java第三方注解

Spring注解
参考文章 作者:陈袁

SpringBoot注解
作者 tanwei81 博客园

3.自定义注解

  1. //使用@interface定义注解
  2. // CONSTRUCTOR:构造方法声明 FIELD:字段 LOCAL_VARIABLE:局部变量
  3. // METHOD:方法 PACKAGE:包 PARAMETER:参数 TYPE:接口.类
  4. @Target({ElementType.CONSTRUCTOR, ElementType.METHOD,ElementType.ANNOTATION_TYPE})
  5. // 存在范围 source:编译时忽略掉
  6. @Retention(RetentionPolicy.RUNTIME)
  7. @Inherited//允许子类(子注解)继承,对接口继承没有作用[extends]
  8. @Documented//生成javadoc会包含注解信息
  9. public @interface Description{
  10. //成员变量以无参无异常的方式声明
  11. //成员类型受限于8种基本类型和String,Class,Annotation,Enumeration
  12. String desc();
  13. String author();
  14. int age() default 18;
  15. }
  16. //只有一个成员变量时,名称必须为value(),使用时可忽略'='或成员名
  17. public @interface Description{
  18. String value();
  19. }
  20. //没有成员的注解成为标识注解
  21. public @interface Description{
  22. }

8种基本类型: byte,short,int,long,float,double,char,boolean

元注解: 给注解进行注解

  1. // CONSTRUCTOR:构造方法声明 FIELD:字段 LOCAL_VARIABLE:局部变量
  2. // METHOD:方法 PACKAGE:包 PARAMETER:参数 TYPE:接口.类
  3. @Target({ElementType.CONSTRUCTOR, ElementType.METHOD,ElementType.ANNOTATION_TYPE})
  4. @Retention(RetentionPolicy.RUNTIME)
  5. @Documented
  6. @Inherited//注解会被子类继承
  7. public @interface Autowired {
  8. /**
  9. * Declares whether the annotated dependency is required.
  10. * <p>Defaults to {@code true}.
  11. */
  12. boolean required() default true;
  13. }

java注解 - 图1

解析注释

  1. try{
  2. //1.找到类上的注解,反射加载类
  3. Class c = Class.forName("com.zjy.entity.Child");
  4. //2.找到类上面的注解
  5. boolean isExist = c.isAnnotationPresent(Description.class);
  6. if(isExist){
  7. //3.存在注解实例,取出
  8. Description d = (Description)c.getAnnotation(Description.class);
  9. System.out.println(d.value());
  10. }
  11. //1.找到方法上的注解
  12. Method[] ms = c.getMethods();
  13. for(Method m : ms){
  14. boolean isExist = m.isAnnotationPresent(Description.class);
  15. if(isExist){
  16. //2.存在注解实例,取出
  17. Description d = (Description)c.getAnnotation(Description.class);
  18. System.out.println(d.value());
  19. }
  20. }
  21. //1.找到方法所有注解
  22. for(Method m : ms){
  23. Annotation[] as = m.getAnnotations();
  24. for(Annotation a: as){
  25. if(a instanceod Description){
  26. Description d = (Description)a;
  27. System.out.println(d.value());
  28. }
  29. }
  30. }
  31. }catch(ClassNotFoundException e){
  32. logger.error("",e);
  33. }

实例

  1. import org.springframework.stereotype.Component;
  2. import java.lang.annotation.Documented;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. @Retention(RetentionPolicy.RUNTIME)
  6. @Documented
  7. @Component//作为左键能被spring扫描到
  8. public @interface SQLFileAnnotation {
  9. String SQLFileName();
  10. }

主方法内扫描注解

  1. public static void scannerBeans(){
  2. //扫描SQL文件注解
  3. String[] sqlFiles = applicationContext.getBeanNamesForAnnotation(SQLFileAnnotation.class);
  4. List<String> sqlFileNameList = new ArrayList<>();
  5. for(String string:sqlFiles){
  6. Object sqlFile = applicationContext.getBean(string);
  7. String sqlFileName = sqlFile.getClass().getAnnotation(SQLFileAnnotation.class).SQLFileName();
  8. sqlFileNameList.add(sqlFileName);
  9. }
  10. executeSql(sqlFileNameList);
  11. }
  12. private static void executeSql(List<String> sqlFileNameList){
  13. Collections.sort(sqlFileNameList, new Comparator<String>() {
  14. @Override
  15. public int compare(String o1, String o2) {
  16. if(o1.contains("-")){
  17. o1 = o1.substring(o1.indexOf("-") + 1,o1.length());
  18. }
  19. if(o2.contains("-")){
  20. o2 = o2.substring(o2.indexOf("-") + 1,o2.length());
  21. }
  22. return o1.compareTo(o2);
  23. }
  24. });
  25. for(String name : sqlFileNameList){
  26. String importedDBs = getImportedDBs();
  27. if(importedDBs.contains(name)){
  28. logger.debug("数据库已导入,不再重复导入!!");
  29. continue;
  30. }
  31. boolean isSuccess = false;
  32. try {
  33. String content = "";
  34. try {
  35. content = IOUtils.toString(new FileInputStream(PathUtil.getPath(PathUtil.PathType.CONFIG)+ "sqlitemanagerTool.sql"),"utf-8");
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. isSuccess = JdbcUtil.getInstance().insertSqlArray(content.split("#970126#"));
  40. } catch (Exception e) {
  41. e.printStackTrace();
  42. }
  43. if(isSuccess){
  44. updateImportedDB(importedDBs + "\r\n" + name);
  45. }
  46. }
  47. }
  48. private static String getImportedDBs(){
  49. StringBuilder importedDB=new StringBuilder();
  50. try {
  51. File file =new File(PathUtil.getPath(PathUtil.PathType.CONFIG) + "dbImport.txt");
  52. if(!file.exists()){
  53. file.createNewFile();
  54. }
  55. FileInputStream in=new FileInputStream(file);
  56. byte[] b=new byte[1024];
  57. int i;
  58. while((i=in.read(b))>0){
  59. importedDB.append(new String(b,0,i));
  60. }
  61. in.close();
  62. }catch (Exception e){
  63. e.printStackTrace();
  64. }
  65. return importedDB.toString();
  66. }
  67. private static void updateImportedDB(String string){
  68. try {
  69. File file =new File(PathUtil.getPath(PathUtil.PathType.CONFIG) + "dbImport.txt");
  70. FileOutputStream out =new FileOutputStream(file);
  71. byte[] newb = string.getBytes();
  72. out.write(newb);
  73. out.close();
  74. }catch (Exception e){
  75. e.printStackTrace();
  76. }
  77. }