HK2工厂单例装订

时间:2019-04-19 21:33:08

标签: java singleton factory hk2

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

1 个答案:

答案 0 :(得分:-1)

AccessTokenProviderFactory.java

--timeout 300

DependencyBinder.java,它扩展了AbstractBinder

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) {
    }

}

Applications配置类,向您展示我如何注册DepedencyBinder。

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