Determine ServiceLocator has no user defined services

你说的曾经没有我的故事 提交于 2019-12-13 05:27:41

问题


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!



来源:https://stackoverflow.com/questions/34433454/determine-servicelocator-has-no-user-defined-services

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!