确定ServiceLocator没有用户定义的服务 [英] Determine ServiceLocator has no user defined services

查看:138
本文介绍了确定ServiceLocator没有用户定义的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个可重用的组件,该组件根据居民文件中定义的服务创建一个ServiceLocator.我需要确定ServiceLocator是否具有除内置服务之外的服务.如果没有,则可能向用户记录一些警告.像

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.");
}

这当然是行不通的,因为services仍然包含所有内置服务.我可以像创建Filter一样

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());

这在 now 上有效,但这不是一个很好的解决方案,因为这些类可以随时更改.

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

因此,我只是想知道是否有任何标准方法来检查ServiceLocator是否具有内置服务之外的任何服务.或其他一些变通方法,不像上面的Filter那样脆弱.

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.

推荐答案

在hk2-locator模块中最新版本的hk2中,有一个API可返回您要查找的过滤器:

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

Hk2LocatorUtilities

这必须在实现模块中,因为另一个实现可能具有一组不同的初始服务,因此这不是一般功能.鉴于此,我不知道hk2的其他实现,因此它仍然相当通用!

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!

这篇关于确定ServiceLocator没有用户定义的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆