泽西2 + HK2 - 自动绑定classess

dee*_*eem 5 java jersey-2.0 hk2

继续主题 泽西2 + HK2 - @ApplicationScoped无效.

我已经知道了,如何@Inject正确地绑定类.

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

小智 5

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

我也发现必须明确绑定每个服务的想法是一种糟糕的代码味道。对于需要使用特殊的构建步骤和为填充器添加的初始化代码,我也不感到疯狂。

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

/**
 * 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;
    }
} 
Run Code Online (Sandbox Code Playgroud)

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

bind( JustInTimeServiceResolver.class ).to( JustInTimeInjectionResolver.class );
Run Code Online (Sandbox Code Playgroud)

我可以像在 Guice 中一样自动创建绑定。