泽西2 + HK2 - 自动绑定classess [英] Jersey 2 + HK2 - automatic binding of classess

查看:161
本文介绍了泽西2 + HK2 - 自动绑定classess的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

主题延续
Jersey 2 + HK2 - @ ApplicationScoped无效

我已经知道,如何绑定类以便 @Inject 他们正确。

I already know, how to bind classes in order to @Inject them properly.

您有什么想法,如何自动化这个过程?将每个服务放在 bind 语句中似乎在我的应用程序中非常难闻。

Do you have any ideas, how to automize this process? Putting every single service in bind statements seems like very bad smell in my application.

推荐答案

使用谷歌的Guice多年后,我已经习惯了Just-In-Time活页夹的可用性,允许注入任意类型而无需任何前期配置。

After using Google's Guice for a number of years, I am accustomed to the availability of a Just-In-Time binder, allowing the injection of arbitrary types without requiring any upfront configuration.

我也发现必须明确地将每个服务绑定为代码异味的想法。我也不会为使用特殊构建步骤和为populator添加初始化代码的需要而疯狂。

I too found the idea of having to explicitly bind every service to be a bad code smell. I'm also not crazy about the need to use a special build step and the added initialization code for the populator.

所以我想出了以下 JustInTimeResolver 实施:

So I came up with the following JustInTimeResolver implementation:

/**
 * Mimic GUICE's ability to satisfy injection points automatically,
 * without needing to explicitly bind every class, and without needing
 * to add an extra build step.
 */
@Service
public class JustInTimeServiceResolver implements JustInTimeInjectionResolver {

    @Inject
    private ServiceLocator serviceLocator;

    @Override
    public boolean justInTimeResolution( Injectee injectee ) {
    final Type requiredType = injectee.getRequiredType();

        if ( injectee.getRequiredQualifiers().isEmpty() && requiredType instanceof Class ) {
            final Class<?> requiredClass = (Class<?>) requiredType;

            // IMPORTANT: check the package name, so we don't accidentally preempt other framework JIT resolvers
            if ( requiredClass.getName().startsWith( "com.fastmodel" )) {
                final List<ActiveDescriptor<?>> descriptors = ServiceLocatorUtilities.addClasses( serviceLocator, requiredClass );

                if ( !descriptors.isEmpty() ) {
                    return true;
                }
            }
        }
        return false;
    }
} 

在我的项目中,我只需添加以下内容我的Jersey应用程序配置中的我的活页夹:

With this in my project, I simply added the following to my binder in my Jersey application configuration:

bind( JustInTimeServiceResolver.class ).to( JustInTimeInjectionResolver.class );

我得到的自动绑定创建就像我在Guice中所做的那样。

and I get automatic binding creation like I did in Guice.

这篇关于泽西2 + HK2 - 自动绑定classess的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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