编程语言
首页 > 编程语言> > java – Jersey 2 HK2 – classess的自动绑定

java – Jersey 2 HK2 – classess的自动绑定

作者:互联网

继续主题
Jersey 2 + HK2 – @ApplicationScoped not working.

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

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

解决方法:

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

我也发现必须明确地将每个服务绑定为一个糟糕的代码气味的想法.我也没有为使用特殊构建步骤和添加的populator初始化代码的需要而疯狂.

所以我提出了以下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;
    }
} 

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

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

我像Guice那样得到自动绑定创建.

标签:java,jersey-2-0,hk2
来源: https://codeday.me/bug/20190519/1134987.html