摘要:之前的作用范围其中驱动通常使用来引入所需要的驱动。在编译期间不用引入具体的具体实现类不管还是等。所以包的应该设置为。用于从中找到接口的实现类。文件中有两个驱动名。而不是通过来找实现类的。是通过找一个固定包下的固定类类而是找固定文件下的内容。
之前
maven 的runtime作用范围
其中JDBC驱动通常使用Class.forName("com.mysql.jdbc.Driver");来引入所需要的驱动。在编译期间不用引入具体jdbc的具体实现类(不管mysql还是oracle等)。所以JDBC包的scope应该设置为runtime。
mysql mysql-connector-java ${mysql.driver.version} runtime
JDBC4之后使用SPI技术 也不用写Class.forName了
Service Provider InterfaceJava API提供的使用ServiceLoader来实现的控制反转工具类。用于从classpath中找到接口的实现类。
先定义一个接口
package ch.frankel.blog.serviceloader; public interface Foo { }
再定义两个实现类(实现类可能是其他工程中定义的)
package ch.frankel.blog.serviceloader; public class FooImpl1 implements Foo { } public class FooImpl2 implements Foo { }
然后在Resources/META-INF下的service中新建一个与接口名对应的文件ch.frankel.blog.serviceloader.Foo
ch.frankel.blog.serviceloader.FooImpl1 ch.frankel.blog.serviceloader.FooImpl2
serviceLoader会从该文件中找到要加载的类。
public class JavaServiceLoaderTest { @Test public void java_service_loader_should_load_correct_implementations() { //Service.load会从ch.frankel.blog.serviceloader.Foo中找到要加载的类,然后加载。 ServiceLoaderSpring 集成 ServiceLoaderloader = ServiceLoader.load(Foo.class); List foos = new ArrayList<>(); loader.iterator().forEachRemaining(foos::add); assertThat(foos) .isNotNull() .isNotEmpty() .hasSize(2); } }
首先需要配置对应的factoryBean
@Configuration public class ServiceConfiguration { @Bean public ServiceListFactoryBean serviceListFactoryBean() { ServiceListFactoryBean serviceListFactoryBean = new ServiceListFactoryBean(); serviceListFactoryBean.setServiceType(Foo.class); return serviceListFactoryBean; } }
然后通过ServiceListFactoryBean就可以找到接口对应的实现类。
@ContextConfiguration(classes = ServiceConfiguration.class) public class ServiceLoaderWithSpringTest extends AbstractTestNGSpringContextTests { @Autowired private ServiceListFactoryBean serviceListFactoryBean; @Test public void spring_service_loader_integration_should_load_correct_implementations() throws Exception { Object object = serviceListFactoryBean.getObject(); Assertions.assertThat(object) .isNotNull() .asList() .isNotEmpty() .hasSize(2); } }Spring Facotories Loader
spring 自己也提供了类似的工具类。使用起来更方便。
首先在META-INF下建立一个spring.factories文件。
ch.frankel.blog.serviceloader.Foo=ch.frankel.blog.serviceloader.FooImpl1,ch.frankel.blog.serviceloader.FooImpl2
直接指定接口对应的实现类。
然后通过Spring提供的静态方法SpringFactoriesLoader就可以直接使用了。
public class SpringFactoriesTest { @Test public void spring_factories_should_load_correct_implementations() { ListService Provider Interface的应用 JDBC SPIfoos = SpringFactoriesLoader.loadFactories(Foo.class, null); assertThat(foos) .isNotNull() .isNotEmpty() .hasSize(2); } }
查看jdbc的代码
//java.sql.DriverManager public class DriverManager { /** * Load the initial JDBC drivers by checking the System property * jdbc.properties and then use the {@code ServiceLoader} mechanism */ static { loadInitialDrivers(); println("JDBC DriverManager initialized"); } private static void loadInitialDrivers() { String drivers; try { drivers = AccessController.doPrivileged(new PrivilegedAction() { public String run() { //从系统变量中获取jdbc.drivers //System.getProperty 可以在vm arguments中设置。java -Djdbc.drivers=xxxx return System.getProperty("jdbc.drivers"); } }); } catch (Exception ex) { drivers = null; } // If the driver is packaged as a Service Provider, load it. // Get all the drivers through the classloader // exposed as a java.sql.Driver.class service. // ServiceLoader.load() replaces the sun.misc.Providers() AccessController.doPrivileged(new PrivilegedAction () { public Void run() { ServiceLoader loadedDrivers = ServiceLoader.load(Driver.class); Iterator driversIterator = loadedDrivers.iterator(); /* Load these drivers, so that they can be instantiated. * It may be the case that the driver class may not be there * i.e. there may be a packaged driver with the service class * as implementation of java.sql.Driver but the actual class * may be missing. In that case a java.util.ServiceConfigurationError * will be thrown at runtime by the VM trying to locate * and load the service. * * Adding a try catch block to catch those runtime errors * if driver not available in classpath but it"s * packaged as service and that service is there in classpath. */ try{ while(driversIterator.hasNext()) { driversIterator.next(); } } catch(Throwable t) { // Do nothing } return null; } }); println("DriverManager.initialize: jdbc.drivers = " + drivers); if (drivers == null || drivers.equals("")) { return; } //多个drivers? String[] driversList = drivers.split(":"); println("number of Drivers:" + driversList.length); for (String aDriver : driversList) { try { println("DriverManager.Initialize: loading " + aDriver); //还是使用Class.forName来加载驱动 Class.forName(aDriver, true, ClassLoader.getSystemClassLoader()); } catch (Exception ex) { println("DriverManager.Initialize: load failed: " + ex); } } } }
在jdbc的实现包中META-INF下有java.sql.Driver文件。
com.mysql.jdbc.Driver com.mysql.fabric.jdbc.FabricMySQLDriver
文件中有两个驱动名。
其实jdbc可以同时管理多个驱动,(jdbc详解:2、DriverManager管理多个数据库驱动)
Commons-Logging//org.apache.commons.logging.LogFactory#getFactory public static LogFactory getFactory() throws LogConfigurationException { ... // Second, try to find a service by using the JDK1.3 class // discovery mechanism, which involves putting a file with the name // of an interface class in the META-INF/services directory, where the // contents of the file is a single line specifying a concrete class // that implements the desired interface. if (factory == null) { if (isDiagnosticsEnabled()) { logDiagnostic( "[LOOKUP] Looking for a resource file of name [" + SERVICE_ID + "] to define the LogFactory subclass to use..."); } try { InputStream is = getResourceAsStream(contextClassLoader, SERVICE_ID); if( is != null ) { // This code is needed by EBCDIC and other strange systems. // It"s a fix for bugs reported in xerces BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(is, "UTF-8")); } catch (java.io.UnsupportedEncodingException e) { rd = new BufferedReader(new InputStreamReader(is)); } String factoryClassName = rd.readLine(); rd.close(); if (factoryClassName != null && ! "".equals(factoryClassName)) { if (isDiagnosticsEnabled()) { logDiagnostic( "[LOOKUP] Creating an instance of LogFactory class " + factoryClassName + " as specified by file "" + SERVICE_ID + "" which was present in the path of the context" + " classloader."); } factory = newFactory(factoryClassName, baseClassLoader, contextClassLoader ); } } else { // is == null if (isDiagnosticsEnabled()) { logDiagnostic( "[LOOKUP] No resource file with name "" + SERVICE_ID + "" found."); } } } catch( Exception ex ) { // note: if the specified LogFactory class wasn"t compatible with LogFactory // for some reason, a ClassCastException will be caught here, and attempts will // continue to find a compatible class. if (isDiagnosticsEnabled()) { logDiagnostic( "[LOOKUP] A security exception occurred while trying to create an" + " instance of the custom factory class" + ": [" + ex.getMessage().trim() + "]. Trying alternative implementations..."); } ; // ignore } } ... }
其中也使用到SPI。从 META-INF/services/org.apache.commons.logging.LogFactory中找要加载的实现类(Apache Commons Logging 是如何决定使用哪个日志实现类的)。
slf4j而slf4j不是通过SPI来找实现类的。slf4j 1.7是通过找一个固定包下的固定类StaticLoggerBinder类(而SPI是找固定文件下的内容)。这个类定义在各个实现包中。
貌似slf4j 1.8 开始使用SPI了,如下图。
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/71203.html
摘要:通过注解引入对象。添加一个使用接收请求添加账号访问层添加微服务启动类链接数据库通过编写数据库访问。 SpringCloud(第 041 篇)链接Mysql数据库,通过JdbcTemplate编写数据库访问 - 一、大致介绍 1、前面章节提到了JPA操作访问数据库,本章节我们讲解一下如何用JdbcTemplate操作访问数据库; 2、使用JdbcTemplate是一个相对更底层的操作,可...
摘要:一考虑用静态工厂方法代替构造器构造器是创建一个对象实例的最基本最常用的方法。开发者在使用某个类的时候,通常会使用一个构造器来实现,其实也有其他方式可以实现的,如利用发射机制。 一、考虑用静态工厂方法代替构造器 构造器是创建一个对象实例的最基本最常用的方法。开发者在使用某个类的时候,通常会使用new一个构造器来实现,其实也有其他方式可以实现的,如利用发射机制。这里主要说的是通过静态类工...
摘要:添加用户接口类实现类简单用户链接数据库微服务通过注解标注该类为持久化操作对象。添加一个使用接收请求添加微服务启动类链接数据库简单的集成框架采用访问数据库。 SpringCloud(第 044 篇)链接Mysql数据库简单的集成Mybatis框架采用MapperXml访问数据库 - 一、大致介绍 1、前面章节讲解的是在方法上面添加sql语句操作,虽然说仅仅只是一种简单的操作,在测试期间可...
阅读 759·2021-11-18 10:02
阅读 2407·2021-11-11 16:54
阅读 2704·2021-09-02 09:45
阅读 623·2019-08-30 12:52
阅读 2621·2019-08-29 14:04
阅读 2707·2019-08-29 12:39
阅读 402·2019-08-29 12:27
阅读 1866·2019-08-26 13:23