mybatis之ResolverUtil工具类

ResolverUtil工具类

* ResolverUtil 用来定位某个class路径下满足任意条件的类们。通常的筛选条件是:
 * 类继承了某个接口
 * 实现了某个类
 * 类拥有可定的注解
 * 基于Test类可以用来判断某各类是否满足这些条件
 
 
 public class ResolverUtil<T> {
  /*
   * An instance of Log to use for logging in this class.
   */
  private static final Log log = LogFactory.getLog(ResolverUtil.class);

  /**
   * A simple interface that specifies how to test classes to determine if they
   * are to be included in the results produced by the ResolverUtil.
   */
  public interface Test {
    /**
     * Will be called repeatedly with candidate classes. Must return True if a class
     * is to be included in the results, false otherwise.
     */
    boolean matches(Class<?> type);
  }

  /**
   * A Test that checks to see if each class is assignable to the provided class. Note
   * that this test will match the parent type itself if it is presented for matching.
   */
  public static class IsA implements Test {
    private Class<?> parent;

    /** Constructs an IsA test using the supplied Class as the parent class/interface. */
    public IsA(Class<?> parentType) {
      this.parent = parentType;
    }

    /** Returns true if type is assignable to the parent type supplied in the constructor. */
    @Override
    public boolean matches(Class<?> type) {
      return type != null && parent.isAssignableFrom(type);
    }

    @Override
    public String toString() {
      return "is assignable to " + parent.getSimpleName();
    }
  }

  /**
   * A Test that checks to see if each class is annotated with a specific annotation. If it
   * is, then the test returns true, otherwise false.
   */
  public static class AnnotatedWith implements Test {
    private Class<? extends Annotation> annotation;

    /** Constructs an AnnotatedWith test for the specified annotation type. */
    public AnnotatedWith(Class<? extends Annotation> annotation) {
      this.annotation = annotation;
    }

    /** Returns true if the type is annotated with the class provided to the constructor. */
    @Override
    public boolean matches(Class<?> type) {
      return type != null && type.isAnnotationPresent(annotation);
    }

    @Override
    public String toString() {
      return "annotated with @" + annotation.getSimpleName();
    }
  }

  /** The set of matches being accumulated. */
  private Set<Class<? extends T>> matches = new HashSet<>();

  /**
   * The ClassLoader to use when looking for classes. If null then the ClassLoader returned
   * by Thread.currentThread().getContextClassLoader() will be used.
   */
  private ClassLoader classloader;

  /**
   * Provides access to the classes discovered so far. If no calls have been made to
   * any of the {@code find()} methods, this set will be empty.
   *
   * @return the set of classes that have been discovered.
   */
  public Set<Class<? extends T>> getClasses() {
    return matches;
  }

  /**
   * Returns the classloader that will be used for scanning for classes. If no explicit
   * ClassLoader has been set by the calling, the context class loader will be used.
   *
   * @return the ClassLoader that will be used to scan for classes
   */
  public ClassLoader getClassLoader() {
    return classloader == null ? Thread.currentThread().getContextClassLoader() : classloader;
  }

  /**
   * Sets an explicit ClassLoader that should be used when scanning for classes. If none
   * is set then the context classloader will be used.
   *
   * @param classloader a ClassLoader to use when scanning for classes
   */
  public void setClassLoader(ClassLoader classloader) {
    this.classloader = classloader;
  }

  /**
   * Attempts to discover classes that are assignable to the type provided. In the case
   * that an interface is provided this method will collect implementations. In the case
   * of a non-interface class, subclasses will be collected.  Accumulated classes can be
   * accessed by calling {@link #getClasses()}.
   *
   * @param parent the class of interface to find subclasses or implementations of
   * @param packageNames one or more package names to scan (including subpackages) for classes
   */
  public ResolverUtil<T> findImplementations(Class<?> parent, String... packageNames) {
    if (packageNames == null) {
      return this;
    }

    Test test = new IsA(parent);
    for (String pkg : packageNames) {
      find(test, pkg);
    }

    return this;
  }

  /**
   * Attempts to discover classes that are annotated with the annotation. Accumulated
   * classes can be accessed by calling {@link #getClasses()}.
   *
   * @param annotation the annotation that should be present on matching classes
   * @param packageNames one or more package names to scan (including subpackages) for classes
   */
  public ResolverUtil<T> findAnnotated(Class<? extends Annotation> annotation, String... packageNames) {
    if (packageNames == null) {
      return this;
    }

    Test test = new AnnotatedWith(annotation);
    for (String pkg : packageNames) {
      find(test, pkg);
    }

    return this;
  }

  /**
   * Scans for classes starting at the package provided and descending into subpackages.
   * Each class is offered up to the Test as it is discovered, and if the Test returns
   * true the class is retained.  Accumulated classes can be fetched by calling
   * {@link #getClasses()}.
   *
   * @param test an instance of {@link Test} that will be used to filter classes
   * @param packageName the name of the package from which to start scanning for
   *        classes, e.g. {@code net.sourceforge.stripes}
   */
  /**
   * 筛选出指定路径下符合一定条件的类
   * @param test 测试条件
   * @param packageName 路径
   * @return ResolverUtil本身
   */
  public ResolverUtil<T> find(Test test, String packageName) {
    // 获取起始包路径
    String path = getPackagePath(packageName);
    try {
      // 找出包中的各个文件
      List<String> children = VFS.getInstance().list(path);
      for (String child : children) {
        // 对类文件进行测试
        if (child.endsWith(".class")) { // 必须是类文件
          // 测试是否满足测试条件。如果满足,则将该类文件记录下来
          addIfMatching(test, child);
        }
      }
    } catch (IOException ioe) {
      log.error("Could not read package: " + packageName, ioe);
    }
    return this;
  }

  /**
   * Converts a Java package name to a path that can be looked up with a call to
   * {@link ClassLoader#getResources(String)}.
   *
   * @param packageName The Java package name to convert to a path
   */
  protected String getPackagePath(String packageName) {
    return packageName == null ? null : packageName.replace('.', '/');
  }

  /**
   * Add the class designated by the fully qualified class name provided to the set of
   * resolved classes if and only if it is approved by the Test supplied.
   *
   * @param test the test used to determine if the class matches
   * @param fqn the fully qualified name of a class
   */
  /**
   * 判断一个类文件是否满足条件。如果满足则记录下来
   * @param test 测试条件
   * @param fqn 类文件全名
   */
  @SuppressWarnings("unchecked")
  protected void addIfMatching(Test test, String fqn) {
    try {
      // 转化为外部名称
      String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
      // 类加载器
      ClassLoader loader = getClassLoader();
      if (log.isDebugEnabled()) {
        log.debug("Checking to see if class " + externalName + " matches criteria [" + test + "]");
      }
      // 加载类文件
      Class<?> type = loader.loadClass(externalName);
      if (test.matches(type)) { // 执行测试
        // 测试通过则记录到matches属性中
        matches.add((Class<T>) type);
      }
    } catch (Throwable t) {
      log.warn("Could not examine class '" + fqn + "'" + " due to a " +
          t.getClass().getName() + " with message: " + t.getMessage());
    }
  }
}

ResolverUtil 用来定位某个class路径下满足任意条件的类们。通常的筛选条件是:

  • 类继承了某个接口
  • 实现了某个类
  • 类拥有可定的注解
  • 基于Test类可以用来判断某各类是否满足这些条件

ResolverUtil拥有两个内部类

  • isA --用于检测指定类是否实现了某个类
  • AnnotatedWith – 用于检测指定类是否添加了指定注解

isA

public static class IsA implements Test {
    private Class<?> parent;

    /** Constructs an IsA test using the supplied Class as the parent class/interface. */
    public IsA(Class<?> parentType) {
      this.parent = parentType;
    }

    /** Returns true if type is assignable to the parent type supplied in the constructor. */
    @Override
    public boolean matches(Class<?> type) {
      return type != null && parent.isAssignableFrom(type);
    }

    @Override
    public String toString() {
      return "is assignable to " + parent.getSimpleName();
    }
  }
  • parent.isAssignableFrom(type);

判断parent对应的类是否是type对应类以及是否type类的父类

AnnotatedWith

public static class AnnotatedWith implements Test {
    private Class<? extends Annotation> annotation;

    /** Constructs an AnnotatedWith test for the specified annotation type. */
    public AnnotatedWith(Class<? extends Annotation> annotation) {
      this.annotation = annotation;
    }

    /** Returns true if the type is annotated with the class provided to the constructor. */
    @Override
    public boolean matches(Class<?> type) {
      return type != null && type.isAnnotationPresent(annotation);
    }

    @Override
    public String toString() {
      return "annotated with @" + annotation.getSimpleName();
    }
  }

首先通过初始化添加需要的检验的注解的Class类
然后调用matches方法来判断:

  • type.isAnnotationPresent(annotation);

type类是否含有annotion对应的注解类

  • A.isAnnotationPresent(B.class); 大白话:B类型的注解是否在A类上。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface B {        //这是一个自定义注解
	String value();
}

@B("/hello")
public class A{

}

基于Test类可以用来判断某各类是否满足这些条件

默认情况下,使用 Thread.currentThread().getContextClassLoader()这个类加载器加载符合条件的类,我们可以在调用find()方法之前,调用setClassLoader(ClassLoader)设置需要使用的ClassLoader,这个ClassLoader可以从ClassLoaderWrapper获取合适的类加载器。

findImplementations()和findAnnotated()都是用来依赖于find()方法,findImplementations是使用isA来检测,findAnnotated是依赖于AnnotatedWith类来检测,他们最后都调用了find()方法

在这里插入图片描述

findImplementations(Class<?>,String …)
public ResolverUtil<T> findImplementations(Class<?> parent, String... packageNames) {
    if (packageNames == null) {
      return this;
    }

    Test test = new IsA(parent);
    for (String pkg : packageNames) {
      find(test, pkg);
    }

    return this;
  }
findAnnotated(Class<? exnteds Annotation>,String …)
public ResolverUtil<T> findAnnotated(Class<? extends Annotation> annotation, String... packageNames) {
    if (packageNames == null) {
      return this;
    }

    Test test = new AnnotatedWith(annotation);
    for (String pkg : packageNames) {
      find(test, pkg);
    }

    return this;
  }

find(Test,String)

/**
   * 筛选出指定路径下符合一定条件的类
   * @param test 测试条件
   * @param packageName 路径
   * @return ResolverUtil本身
   */
  public ResolverUtil<T> find(Test test, String packageName) {
    // 获取起始包路径
    String path = getPackagePath(packageName);
    try {
      // 找出包中的各个文件
      List<String> children = VFS.getInstance().list(path);
      for (String child : children) {
        // 对类文件进行测试
        if (child.endsWith(".class")) { // 必须是类文件
          // 测试是否满足测试条件。如果满足,则将该类文件记录下来
          addIfMatching(test, child);
        }
      }
    } catch (IOException ioe) {
      log.error("Could not read package: " + packageName, ioe);
    }
    return this;
  }
addIfMatching(Test test, String fqn)
/**
  * 判断一个类文件是否满足条件。如果满足则记录下来
  * @param test 测试条件
  * @param fqn 类文件全名
  */
 @SuppressWarnings("unchecked")
 protected void addIfMatching(Test test, String fqn) {
   try {
     // 转化为外部名称
     String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
     // 类加载器
     ClassLoader loader = getClassLoader();
     if (log.isDebugEnabled()) {
       log.debug("Checking to see if class " + externalName + " matches criteria [" + test + "]");
     }
     // 加载类文件
     Class<?> type = loader.loadClass(externalName);
     if (test.matches(type)) { // 执行测试
       // 测试通过则记录到matches属性中
       matches.add((Class<T>) type);
     }
   } catch (Throwable t) {
     log.warn("Could not examine class '" + fqn + "'" + " due to a " +
         t.getClass().getName() + " with message: " + t.getMessage());
   }
 }

小Demo:

public class Test {
   public static void main(String[] args) {
       ResolverUtil resolverUtil = new ResolverUtil();
       resolverUtil.findImplementations(Object.class,"org.Hikari.bean");
       resolverUtil.findAnnotated(Mapper.class,"org.Hikari.bean");
       Set classes = resolverUtil.getClasses();
       Iterator iterator = classes.iterator();
       while (iterator.hasNext()) {
           Class clazz = (Class) iterator.next();
           System.out.println(clazz.getName());
       }
   }
}
org.Hikari.bean.People
org.Hikari.bean.Student
org.Hikari.bean.User
org.Hikari.bean.Nature
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Mybatis-Plus是一个优秀的Mybatis增强工具,它可以极大地简化Mybatis的开发流程,提高开发效率。下面是一个基于Mybatis-Plus的工具类示例: ```java public class MybatisPlusUtils { /** * 获取MybatisPlus的全局配置对象 * @return GlobalConfig对象 */ public static GlobalConfig getGlobalConfig() { GlobalConfig globalConfig = new GlobalConfig(); //设置主键自增策略 globalConfig.setSqlInjector(new AutoSqlInjector()); globalConfig.setDbConfig(new GlobalConfig.DbConfig() .setLogicDeleteValue("1") .setLogicNotDeleteValue("0") .setIdType(IdType.AUTO)); return globalConfig; } /** * 获取MybatisPlus的数据源对象 * @param driver 数据库驱动 * @param url 数据库连接URL * @param username 数据库用户名 * @param password 数据库密码 * @return DataSource对象 */ public static DataSource getDataSource(String driver, String url, String username, String password) { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } /** * 获取MybatisPlus的SqlSessionFactory对象 * @param dataSource 数据源对象 * @param globalConfig 全局配置对象 * @return SqlSessionFactory对象 */ public static SqlSessionFactory getSqlSessionFactory(DataSource dataSource, GlobalConfig globalConfig) { MybatisConfiguration configuration = new MybatisConfiguration(); //开启驼峰命名规则 configuration.setMapUnderscoreToCamelCase(true); //将全局配置对象添加到Mybatis配置对象中 configuration.setGlobalConfig(globalConfig); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); return builder.build(configuration, new MybatisPlusInterceptor[]{new PaginationInterceptor()}, dataSource); } /** * 获取MybatisPlus的SqlSession对象 * @param sqlSessionFactory SqlSessionFactory对象 * @return SqlSession对象 */ public static SqlSession getSqlSession(SqlSessionFactory sqlSessionFactory) { return sqlSessionFactory.openSession(); } } ``` 使用该工具类,可以方便地获取Mybatis-Plus所需的全局配置、数据源、SqlSessionFactory和SqlSession对象。在使用时,只需要传入相应的参数即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值