JAVA的SPI机制

描述

        JAVA的SPI机制是一种扩展实现,在JDBC中有体现。java中提供数据库操作的接口也就是规范,各数据库厂商提供具体的实现类,也就是驱动。比如mysql的连接驱动会在其jar包的META-INF/service中提供一个文件名为实现的接口名,内容为具体的实现类的全路径。当jar包导入进来之后,DriverManager会自动利用反射实例化。

示例

@Test
    public void testConnection5() {

        try {

            InputStream is = ClassLoader.getSystemResourceAsStream("jdbc.properties");

            Properties properties = new Properties();
            properties.load(is);

            String url=properties.getProperty("url");
            String user=properties.getProperty("user");
            String password=properties.getProperty("password");


            /**
             * 此处注释掉也可以正常运行
             * 因为:用到了java的spi机制,导入的jar包中META-INF/service下
             * 存在接口java.sql.Driver的全路径com.mysql.cj.jdbc.Driver
             * 采用spi机制,接口的发现机制,所以会自动调用此实现类的实例化
             */

//            String classsName="com.mysql.jdbc.Driver";

//            Class.forName(classsName);

//            Class clazz= Class.forName(classsName);
//            Driver driver = (Driver) clazz.newInstance();
//
//            DriverManager.registerDriver(driver);

            Connection connect = DriverManager.getConnection(url, user, password);

            System.out.println(connect);
        } catch (Exception e) {
            e.printStackTrace();
        }

SPI机制代码

@Test
    public void test() throws Exception {

        InputStream is = ClassLoader.getSystemResourceAsStream("jdbc.properties");

        Properties properties = new Properties();
        properties.load(is);


        ServiceLoader<Driver> load = ServiceLoader.load(Driver.class);
        Iterator<Driver> iterator = load.iterator();

        while (iterator.hasNext()){
            Driver driver = iterator.next();
            if (driver instanceof com.mysql.jdbc.Driver){
                Connection connect = driver.connect(properties.getProperty("url"),properties);
                System.out.println(connect);
            }

        }

    }

结果:com.mysql.jdbc.JDBC4Connection@4563e9ab

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值