ServiceLoader无法从模块加载实现

时间:2019-01-08 19:10:21

标签: java jigsaw

我有一个Java程序,该程序由3个模块组成:一个包含服务作为接口的模块,一个包含该接口的实现的模块,一个包含使用该实现的客户端的模块。问题是,在客户端模块Im中使用ServiceLoader加载服务,但是ServiceLoader实例中没有任何服务。

我尝试使用实现模块中provides ... with文件中的关键字module-info.java和客户端模块中的uses,如本教程所述:https://dzone.com/articles/java-9-kickoff-project-jigsaw-and-serviceloader-part-2

module-info.java 来自服务模块

module com.em.common {
    exports com.em.common.model;
}

module-info.java 来自实施模块

module com.em.implementation {
    requires com.em.common;
    provides com.em.common.model.EmployeeService with com.em.implementation.employee.EmployeeServiceImpl;
}
客户端模块中的

module-info.java

module com.em.client {
    requires com.em.common;
    uses com.em.common.model.EmployeeService;
}

EmployeeServiceImpl.java

package com.em.implementation.employee;

import com.em.common.model.Employee;
import com.em.common.model.EmployeeService;

public class EmployeeServiceImpl implements EmployeeService {

    public EmployeeServiceImpl() {
        System.out.println("creating employee");
    }

    public Employee getEmployee(String firstName, String lastName) {

        Employee employee = new Employee();
        employee.setFirstName(firstName);
        employee.setLastName(lastName);
        employee.setDesignation("Unimportant Things Designer");

        return employee;
    }
}

EmployeeServiceTest.java

package com.em.client.employee;

import java.util.ServiceLoader;

import com.em.common.model.EmployeeService;

public class EmployeeServiceTest {

    public static void main(String[] args) {

        ServiceLoader<EmployeeService> loader = ServiceLoader.load(EmployeeService.class);

        System.out.println(loader.iterator().hasNext());

    }

}

System.out.println(loader.iterator().hasNext());打印false的预期时间是true。那里缺少什么?

1 个答案:

答案 0 :(得分:0)

在EmployeeServiceImpl类中添加注解@AutoService(EmployeeService.class) 喜欢

@AutoService(EmployeeService.class) 公共类 EmployeeServiceImpl 实现 EmployeeService {

.....