繁体   English   中英

HK2 工厂单例绑定

[英]HK2 Factory Singleton binding

如何使用具有泛型类型的 AbstractBinder 创建 HK2 工厂类并将其绑定为 Singleton 实例。

AccessTokenProviderFactory.java

package org.bitguiders.api.factories;

import org.bitguiders.util.proivders.AccessTokenProvider;
import org.glassfish.hk2.api.Factory;

public class AccessTokenProviderFactory implements Factory<AccessTokenProvider> {

    @Override
    public AccessTokenProvider provide() {
        return new AccessTokenProvider();
    }
    /**
     * This method will dispose of objects created with this scope.  This method should
     * not be annotated, as it is naturally paired with the provide method
     * 
     * @param instance The instance to dispose of
     */
    public void dispose(AccessTokenProvider instance) {
    }

}

扩展 AbstractBinder 的 DependencyBinder.java

package org.bitguiders.ciam.acc.cfg;

import javax.inject.Singleton;
import org.glassfish.hk2.api.TypeLiteral;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.process.internal.RequestScoped;


public class DependencyBinder extends AbstractBinder{

@Override
protected void configure() {
    bind(AccountManagementServiceImpl.class).to(AccountManagementService.class).in(Singleton.class);
    bindFactory(AccessTokenStoreFactory.class).proxy(true).proxyForSameScope(false).to(AccessTokenStore.class).in(RequestScoped.class);
    bind(CASLocationServiceImpl.class).to(LocationService.class).named(CAS_LOCATION_SERVICE).in(Singleton.class);
    bindAsContract(LocationServiceFactory.class).in(Singleton.class);
// If AccessTokenProvider.java is one of the impl of MyTokenProvider<T> 
//bindFactory(AccessTokenProviderFactory.class).to(AccessTokenProvider.class).to(new TypeLiteral<MyTokenProvider<String>>(){}).in(Singleton.class);
  bindFactory(AccessTokenProviderFactory.class).to(AccessTokenProvider.class).in(Singleton.class);

应用程序配置类向您展示我如何注册 DepedencyBinder。

package org.bitguiders.ciam.acctmgt.cfg

import javax.ws.rs.ApplicationPath;

import org.bitguidres.api.exceptions.GenericExceptionMapper;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;

@ApplicationPath("acc/api/*")
public class ApplicationConfig extends ResourceConfig {
    public ApplicationConfig() {
        packages("org.cas.ciam.acctmgt");
        register(JacksonFeature.class);
        register(GenericExceptionMapper.class);
        register(new DependencyBinder());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM