Determine ServiceLocator has no user defined servi

2019-09-02 07:40发布

问题:

I'm trying to make a reusable component that creates a ServiceLocator from the services defined in the inhabitants file. I need to determine if the ServiceLocator has services apart from the built in ones. If it doesn't, maybe log some warning to the user. Something like

ServiceLocator locator =  ServiceLocatorUtilities.createAndPopulateServiceLocator();
List<?> services = locator.getAllServices(BuilderHelper.allFilter());
if (services.isEmpty()) {
    LOGGER.log(Level.WARNING, 
            "No services. Make sure inhabitants generator is working correctly.");
}

This of course doesn't work because the services still contains all the built in services. I could create a Filter like

public class NonBuiltInFilter implements Filter {

    private static final Set<String> builtInClasses = new HashSet<>(
            Arrays.asList("org.jvnet.hk2.internal.ServiceLocatorImpl",
                          "org.jvnet.hk2.internal.ThreeThirtyResolver",
                          "org.jvnet.hk2.internal.DynamicConfigurationServiceImpl",
                          "org.jvnet.hk2.internal.DefaultClassAnalyzer",
                          "org.jvnet.hk2.internal.ServiceLocatorRuntimeImpl",
                          "org.jvnet.hk2.internal.InstantiationServiceImpl")
    );

    @Override
    public boolean matches(Descriptor d) {
        return !builtInClasses.contains(d.getImplementation());
    } 
}
...
List<?> services = locator.getAllServices(new NonBuiltInFilter());

This works now but it is not a great solution, as those classes could change at any time.

So I'm just wondering if there is any standard way to check if the ServiceLocator has any services, aside from the built in ones. Or some other work-around that is not as fragile as the Filter above.

回答1:

In the latest version of hk2 in the hk2-locator module there is an API that returns the filter you are looking for:

Hk2LocatorUtilities

This has to be in the implementation module because another implementation may have a different set of initial services, so it isn't a general feature. Given that, there are no other implementations of hk2 that I know of, so it's still pretty general!



标签: java hk2