All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.netflix.fabricator.guice.NamedInstanceProvider Maven / Gradle / Ivy

There is a newer version: 0.28.0
Show newest version
package com.netflix.fabricator.guice;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.spi.BindingTargetVisitor;
import com.google.inject.spi.ProviderInstanceBinding;
import com.google.inject.spi.ProviderWithExtensionVisitor;
import com.google.inject.spi.Toolable;
import com.netflix.fabricator.component.ComponentManager;
import com.netflix.fabricator.component.exception.ComponentAlreadyExistsException;
import com.netflix.fabricator.component.exception.ComponentCreationException;

/**
 * Special provider that links a ComponentManager with a named instance of a 
 * Component so that the component may be inject by
 * 
 * void SomeServiceConstructor(@Named("componentId") ComponentType component) {
 * }
 * 
 * To use,
 * 
 *  install(ComponentModuleBuilder().builder()
 *      .named("componentId")
 *      .build());
 *      
 * @author elandau
 *
 * @param 
 */
public class NamedInstanceProvider implements ProviderWithExtensionVisitor  {
    private ComponentManager manager;
    private final String id;
    private TypeLiteral> typeLiteral;
    
    public NamedInstanceProvider(String id, TypeLiteral> typeLiteral) {
        this.id = id;
        this.typeLiteral = typeLiteral;
    }

    @Override
    public T get() {
        try {
            return manager.get(id);
        } 
        catch (ComponentCreationException e) {
            throw new RuntimeException(e);
        }
        catch (ComponentAlreadyExistsException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public  V acceptExtensionVisitor(
            BindingTargetVisitor visitor,
            ProviderInstanceBinding binding) {
        return visitor.visit(binding);
    }

    @Inject
    @Toolable
    void initialize(Injector injector) {
        manager = injector.getInstance(Key.get(typeLiteral));
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy