javax.inject.Qualifier Java Examples

The following examples show how to use javax.inject.Qualifier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Component.java    From AndroidMvc with Apache License 2.0 6 votes vote down vote up
/**
 * Unregister component where methods annotated by {@link Provides} will be registered as
 * injection providers.
 *
 * @param providerHolder The object with methods marked by {@link Provides} to provide injectable
 *                       instances
 * @return this instance
 *
 * @throws ProviderMissingException Thrown when the any provider in the provider holder with
 *  the given type and qualifier cannot be found under this component
 */
public Component unregister(Object providerHolder) throws ProviderMissingException {
    Method[] methods = providerHolder.getClass().getDeclaredMethods();
    for (Method method : methods) {
        if (method.isAnnotationPresent(Provides.class)) {
            Class<?> returnType = method.getReturnType();
            if (returnType != void.class) {
                Annotation qualifier = null;
                Annotation[] annotations = method.getAnnotations();
                for (Annotation a : annotations) {
                    if (a.annotationType().isAnnotationPresent(Qualifier.class)) {
                        qualifier = a;
                        break;
                    }
                }

                unregister(returnType, qualifier);
            }
        }
    }
    return this;
}
 
Example #2
Source File: InjectAnnotationAutowireContextTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testAutowiredFieldDoesNotResolveWithBaseQualifierAndNonDefaultValueAndMultipleMatchingCandidates() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
	cavs1.addGenericArgumentValue("the real juergen");
	RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
	person1.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "juergen"));
	ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
	cavs2.addGenericArgumentValue("juergen imposter");
	RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
	person2.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "juergen"));
	context.registerBeanDefinition("juergen1", person1);
	context.registerBeanDefinition("juergen2", person2);
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedConstructorArgumentWithBaseQualifierNonDefaultValueTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	try {
		context.refresh();
		fail("expected BeanCreationException");
	}
	catch (BeanCreationException e) {
		assertTrue(e instanceof UnsatisfiedDependencyException);
		assertEquals("autowired", e.getBeanName());
	}
}
 
Example #3
Source File: IncludeWebClass.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
private boolean isProduces(Method m)
{
  Annotation []anns = m.getAnnotations();

  if (anns == null) {
    return false;
  }

  for (Annotation ann : anns) {
    if (ann.annotationType().isAnnotationPresent(Qualifier.class)) {
      return true;
    }
  }

  return false;
}
 
Example #4
Source File: InjectAnnotationAutowireContextTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testAutowiredFieldDoesNotResolveWithBaseQualifierAndNonDefaultValueAndMultipleMatchingCandidates() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
	cavs1.addGenericArgumentValue("the real juergen");
	RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
	person1.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "juergen"));
	ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
	cavs2.addGenericArgumentValue("juergen imposter");
	RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
	person2.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "juergen"));
	context.registerBeanDefinition("juergen1", person1);
	context.registerBeanDefinition("juergen2", person2);
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedConstructorArgumentWithBaseQualifierNonDefaultValueTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	try {
		context.refresh();
		fail("expected BeanCreationException");
	}
	catch (BeanCreationException e) {
		assertTrue(e instanceof UnsatisfiedDependencyException);
		assertEquals("autowired", e.getBeanName());
	}
}
 
Example #5
Source File: ObjectGraphBuilderImpl.java    From Spork with Apache License 2.0 6 votes vote down vote up
/**
 * Collect the ObjectGraphNode instances for a specific module.
 */
private static void collectObjectGraphNodes(ReflectionCache reflectionCache, List<ObjectGraphNode> objectGraphNodes, Object module) {
	for (Method method : module.getClass().getDeclaredMethods()) {
		// find a matching method
		if (!method.isAnnotationPresent(Provides.class)) {
			continue;
		}

		if (!Modifier.isPublic(method.getModifiers())) {
			throw new SporkRuntimeException("Module method is not public: " + method.toString());
		}

		// getQualifier key
		Nullability nullability = Nullability.create(method);
		Annotation qualifierAnnotation = Annotations.findAnnotationAnnotatedWith(Qualifier.class, method);
		String qualifier = qualifierAnnotation != null
				? reflectionCache.getQualifier(qualifierAnnotation)
				: null;
		InjectSignature injectSignature = new InjectSignature(method.getReturnType(), nullability, qualifier);
		objectGraphNodes.add(new ObjectGraphNode(injectSignature, module, method));
	}
}
 
Example #6
Source File: InjectSignatureMethodCache.java    From Spork with Apache License 2.0 6 votes vote down vote up
/**
 * Create the InjectSignature for a specific Method parameter.
 */
private InjectSignature createInjectSignature(Method method, int parameterIndex) {
	Class<?> parameterClass = method.getParameterTypes()[parameterIndex];

	Annotation[] annotations = method.getParameterAnnotations()[parameterIndex];
	Nullability nullability = Nullability.create(annotations);
	Class<?> targetType = (parameterClass == Provider.class)
			? (Class<?>) ((ParameterizedType) method.getGenericParameterTypes()[parameterIndex]).getActualTypeArguments()[0]
			: parameterClass;

	Annotation qualifierAnnotation = Annotations.findAnnotationAnnotatedWith(Qualifier.class, annotations);
	String qualifier = qualifierAnnotation != null
			? qualifierCache.getQualifier(qualifierAnnotation)
			: null;

	return new InjectSignature(targetType, nullability, qualifier);
}
 
Example #7
Source File: Component.java    From AndroidMvc with Apache License 2.0 6 votes vote down vote up
private void registerProvides(final Object providerHolder, final Method method)
        throws ProvideException, ProviderConflictException {
    Class<?> returnType = method.getReturnType();
    if (returnType == void.class) {
        throw new ProvideException(String.format("Provides method %s must not return void.",
                method.getName()));
    } else {
        Annotation[] annotations = method.getAnnotations();
        Annotation qualifier = null;
        for (Annotation a : annotations) {
            Class<? extends Annotation> annotationType = a.annotationType();
            if (annotationType.isAnnotationPresent(Qualifier.class)) {
                if (qualifier != null) {
                    throw new ProvideException("Only one Qualifier is supported for Provide method. " +
                            String.format("Found multiple qualifier %s and %s for method %s",
                                    qualifier.getClass().getName(), a.getClass().getName(),
                                    method.getName()));
                }
                qualifier = a;
            }
        }

        Provider provider = new MethodProvider(returnType, qualifier, scopeCache, providerHolder, method);
        register(provider);
    }
}
 
Example #8
Source File: EncryptionServiceBindingFactory.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
private Key<EncryptionService> createKeyFromQualifier(String qualifier) {
    Key<EncryptionService> key;
    Optional<Class<Object>> optionalClass = Classes.optional(qualifier);
    if (optionalClass.isPresent()) {
        Class<?> qualifierClass = optionalClass.get();
        if (!Annotation.class.isAssignableFrom(qualifierClass)
                || !qualifierClass.isAnnotationPresent(Qualifier.class)) {
            throw SeedException.createNew(CryptoErrorCode.INVALID_QUALIFIER_ANNOTATION)
                    .put("qualifier", qualifier);
        } else {
            key = Key.get(EncryptionService.class, qualifierClass.asSubclass(Annotation.class));
        }
    } else {
        key = Key.get(EncryptionService.class, Names.named(qualifier));
    }
    return key;
}
 
Example #9
Source File: InjectAnnotationAutowireContextTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testAutowiredFieldDoesNotResolveWithBaseQualifierAndNonDefaultValueAndMultipleMatchingCandidates() {
	GenericApplicationContext context = new GenericApplicationContext();
	ConstructorArgumentValues cavs1 = new ConstructorArgumentValues();
	cavs1.addGenericArgumentValue("the real juergen");
	RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null);
	person1.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "juergen"));
	ConstructorArgumentValues cavs2 = new ConstructorArgumentValues();
	cavs2.addGenericArgumentValue("juergen imposter");
	RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null);
	person2.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "juergen"));
	context.registerBeanDefinition("juergen1", person1);
	context.registerBeanDefinition("juergen2", person2);
	context.registerBeanDefinition("autowired",
			new RootBeanDefinition(QualifiedConstructorArgumentWithBaseQualifierNonDefaultValueTestBean.class));
	AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
	try {
		context.refresh();
		fail("expected BeanCreationException");
	}
	catch (BeanCreationException e) {
		assertTrue(e instanceof UnsatisfiedDependencyException);
		assertEquals("autowired", e.getBeanName());
	}
}
 
Example #10
Source File: Key.java    From auto with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a key based on the type {@code type} and any {@link Qualifier}s in {@code
 * annotations}.
 *
 * <p>If {@code type} is a {@code Provider<T>}, the returned {@link Key}'s {@link #type()} is
 * {@code T}. If {@code type} is a primitive, the returned {@link Key}'s {@link #type()} is the
 * corresponding {@linkplain Types#boxedClass(PrimitiveType) boxed type}.
 *
 * <p>For example:
 * <table>
 *   <tr><th>Input type                <th>{@code Key.type()}
 *   <tr><td>{@code String}            <td>{@code String}
 *   <tr><td>{@code Provider<String>}  <td>{@code String}
 *   <tr><td>{@code int}               <td>{@code Integer}
 * </table>
 */
static Key create(
    TypeMirror type, Iterable<? extends AnnotationMirror> annotations, Types types) {
  ImmutableSet.Builder<AnnotationMirror> qualifiers = ImmutableSet.builder();
  for (AnnotationMirror annotation : annotations) {
    if (isAnnotationPresent(annotation.getAnnotationType().asElement(), Qualifier.class)) {
      qualifiers.add(annotation);
    }
  }

  // TODO(gak): check for only one qualifier rather than using the first
  Optional<AnnotationMirror> qualifier = FluentIterable.from(qualifiers.build()).first();

  TypeMirror keyType =
      isProvider(type)
          ? MoreTypes.asDeclared(type).getTypeArguments().get(0)
          : boxedType(type, types);
  return new AutoValue_Key(
      MoreTypes.equivalence().wrap(keyType),
      wrapOptionalInEquivalence(AnnotationMirrors.equivalence(), qualifier));
}
 
Example #11
Source File: ReflectUtils.java    From AndroidMvc with Apache License 2.0 5 votes vote down vote up
private static Annotation findFirstQualifierInAnnotations(Annotation[] annotations) {
    if (annotations != null) {
        for (Annotation a : annotations) {
            if (a.annotationType().isAnnotationPresent(Qualifier.class)) {
                return a;
            }
        }
    }

    return null;
}
 
Example #12
Source File: BusinessUtils.java    From business with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Optionally returns the qualifier annotation of a class.
 */
public static Optional<Annotation> getQualifier(AnnotatedElement annotatedElement) {
    AnnotatedElement cleanedAnnotatedElement;
    if (annotatedElement instanceof Class<?>) {
        cleanedAnnotatedElement = ProxyUtils.cleanProxy((Class<?>) annotatedElement);
    } else {
        cleanedAnnotatedElement = annotatedElement;
    }
    return Annotations.on(cleanedAnnotatedElement)
            .findAll()
            .filter(annotationAnnotatedWith(Qualifier.class, false).or(annotationIsOfClass(Named.class)))
            .findFirst();
}
 
Example #13
Source File: InjectorBuilderImpl.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
private boolean isProduces(Annotation []anns)
{
  if (anns == null) {
    return false;
  }

  for (Annotation ann : anns) {
    if (ann.annotationType().isAnnotationPresent(Qualifier.class)) {
      return true;
    }
  }

  return false;
}
 
Example #14
Source File: AdditionExtractor.java    From Auto-Dagger2 with MIT License 5 votes vote down vote up
private AnnotationMirror findQualifier(Element element) {
    List<AnnotationMirror> annotationMirrors = ExtractorUtil.findAnnotatedAnnotation(element, Qualifier.class);
    if (annotationMirrors.isEmpty()) {
        return null;
    }

    if (annotationMirrors.size() > 1) {
        errors.getParent().addInvalid(element, "Cannot have several qualifiers (@Qualifier).");
        return null;
    }

    return annotationMirrors.get(0);
}
 
Example #15
Source File: BindingUtils.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Resolve the key for injectee class, including qualifier from implClass and resolved type variables.
 * <p>
 * Useful when we can not resolve type variable from one implementation.
 *
 * @param injecteeClass       the injectee class
 * @param genericImplClass    the generic implementation
 * @param typeVariableClasses the type variable classes
 * @return {@link com.google.inject.Key}
 */
@SuppressWarnings("unchecked")
public static <T> Key<T> resolveKey(Class<T> injecteeClass, Class<? extends T> genericImplClass,
        Type... typeVariableClasses) {
    Optional<Annotation> qualifier = Annotations.on(genericImplClass)
            .findAll()
            .filter(AnnotationPredicates.annotationAnnotatedWith(Qualifier.class, false))
            .findFirst();
    TypeLiteral<T> genericInterface = (TypeLiteral<T>) TypeLiteral.get(
            Types.newParameterizedType(injecteeClass, typeVariableClasses));
    return qualifier.map(annotation -> Key.get(genericInterface, annotation)).orElseGet(
            () -> Key.get(genericInterface));
}
 
Example #16
Source File: ObjectId.java    From DaggerMock with Apache License 2.0 5 votes vote down vote up
private boolean isQualifier(Class<? extends Annotation> annotationType) {
    Annotation[] annotations = annotationType.getAnnotations();
    for (Annotation annotation : annotations) {
        if (annotation.annotationType().equals(Qualifier.class)) {
            return true;
        }
    }
    return false;
}
 
Example #17
Source File: Bindable.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
private Optional<Annotation> findQualifier(Class<? extends T> target) {
    return Annotations.on(target)
            .traversingSuperclasses()
            .traversingInterfaces()
            .findAll()
            .filter(AnnotationPredicates.annotationAnnotatedWith(Qualifier.class, false))
            .findFirst();
}
 
Example #18
Source File: GuiceAnnotationIntrospector.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
private Annotation findBindingAnnotation(Iterable<Annotation> annotations)
{
    for (Annotation annotation : annotations) {
        // Check on guice (BindingAnnotation) & javax (Qualifier) based injections
        if (annotation.annotationType().isAnnotationPresent(BindingAnnotation.class) ||
            annotation.annotationType().isAnnotationPresent(Qualifier.class))
        {
            return annotation;
        }
    }
    return null;
}
 
Example #19
Source File: BeanSpecTest.java    From java-di with Apache License 2.0 5 votes vote down vote up
@Test
public void testTaggedAnnotation() throws Exception {
    Constructor<LeatherSmoother.Host> constructor = LeatherSmoother.Host.class.getConstructor(LeatherSmoother.class);
    Annotation[] annotations = constructor.getParameterAnnotations()[0];
    Type paramType = constructor.getGenericParameterTypes()[0];
    BeanSpec spec = BeanSpec.of(paramType, annotations, Genie.create());
    eq(1, spec.taggedAnnotations(Qualifier.class).length);
    eq(0, spec.taggedAnnotations(InjectTag.class).length);
    eq(0, spec.taggedAnnotations(Retention.class).length);
    eq(0, spec.taggedAnnotations(Target.class).length);
    eq(0, spec.taggedAnnotations(Inherited.class).length);
    eq(0, spec.taggedAnnotations(Documented.class).length);
}
 
Example #20
Source File: Reflection.java    From dagger-reflect with Apache License 2.0 5 votes vote down vote up
static @Nullable Annotation findQualifier(Annotation[] annotations) {
  Annotation qualifier = null;
  for (Annotation annotation : annotations) {
    if (annotation.annotationType().getAnnotation(Qualifier.class) != null) {
      if (qualifier != null) {
        throw new IllegalArgumentException(
            "Multiple qualifier annotations: " + qualifier + " and " + annotation);
      }
      qualifier = annotation;
    }
  }
  return qualifier;
}
 
Example #21
Source File: Binding.java    From toothpick with Apache License 2.0 5 votes vote down vote up
public <A extends Annotation> CanBeBound withName(
    Class<A> annotationClassWithQualifierAnnotation) {
  if (!annotationClassWithQualifierAnnotation.isAnnotationPresent(Qualifier.class)) {
    throw new IllegalArgumentException(
        String.format(
            "Only qualifier annotation annotations can be used to define a binding name. Add @Qualifier to %s",
            annotationClassWithQualifierAnnotation));
  }
  Binding.this.name = annotationClassWithQualifierAnnotation.getCanonicalName();
  return new CanBeBound();
}
 
Example #22
Source File: InjectSignatureFieldCache.java    From Spork with Apache License 2.0 5 votes vote down vote up
private InjectSignature createInjectSignature(Field field, Class<?> targetType) {
	Annotation qualifierAnnotation = Annotations.findAnnotationAnnotatedWith(Qualifier.class, field);
	Nullability nullability = Nullability.create(field);
	String qualifier = qualifierAnnotation != null
			? qualifierCache.getQualifier(qualifierAnnotation)
			: null;
	return new InjectSignature(targetType, nullability, qualifier);
}
 
Example #23
Source File: CreateMockitoMocksCallback.java    From quarkus with Apache License 2.0 5 votes vote down vote up
static Annotation[] getQualifiers(Field fieldToMock) {
    List<Annotation> qualifiers = new ArrayList<>();
    Annotation[] fieldAnnotations = fieldToMock.getDeclaredAnnotations();
    for (Annotation fieldAnnotation : fieldAnnotations) {
        for (Annotation annotationOfFieldAnnotation : fieldAnnotation.annotationType().getAnnotations()) {
            if (annotationOfFieldAnnotation.annotationType().equals(Qualifier.class)) {
                qualifiers.add(fieldAnnotation);
                break;
            }
        }
    }
    return qualifiers.toArray(new Annotation[0]);
}
 
Example #24
Source File: MicronautBeanFactory.java    From micronaut-spring with Apache License 2.0 5 votes vote down vote up
private String computeBeanName(BeanDefinition<?> definition) {
    String name;
    if (definition instanceof NameResolver) {
        name = ((NameResolver) definition).resolveName().orElse(Primary.class.getSimpleName());
    } else {
        name = definition.getValue(Named.class, String.class).orElseGet(() ->
                definition.getAnnotationTypeByStereotype(Qualifier.class).map(Class::getSimpleName).orElse(definition.getClass().getSimpleName())
        );
    }
    return definition.getBeanType().getName() + "(" + name + ")";
}
 
Example #25
Source File: InjectorBuilderImpl.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
boolean isQualifier(Annotation ann)
{
  Class<?> annType = ann.annotationType();

  if (annType.isAnnotationPresent(Qualifier.class)) {
    return true;
  }

  return _qualifierSet.contains(annType);
}
 
Example #26
Source File: MethodParameterInjectionPoint.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public Set<Annotation> getQualifiers() {
    Set<Annotation> qualifiers = new HashSet<>();
    for (Annotation potentialQualifier : method.getParameterAnnotations()[position]) {
        if (potentialQualifier.annotationType().getAnnotation(Qualifier.class) != null) {
            qualifiers.add(potentialQualifier);
        }
    }
    if (qualifiers.size() == 0) {
        qualifiers.add(Default.Literal.INSTANCE);
    }
    return qualifiers;
}
 
Example #27
Source File: TestParametersSupport.java    From dropwizard-guicey with MIT License 4 votes vote down vote up
private boolean isQualifierAnnotation(final Annotation... annotations) {
    final Annotation ann = annotations[0];
    return annotations.length == 1
            && (AnnotationSupport.isAnnotated(ann.annotationType(), Qualifier.class)
            || AnnotationSupport.isAnnotated(ann.annotationType(), BindingAnnotation.class));
}
 
Example #28
Source File: AnnotationUtilTest.java    From joynr with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetAnnotationForMethodReturnsNullForNonExistentAnnotation() throws Exception {
    Qualifier result = AnnotationUtil.getAnnotation(getMethodWithAnnotation(), Qualifier.class);
    assertNull(result);
}
 
Example #29
Source File: Qualifiers.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private static void verifyQualifier(Class<? extends Annotation> annotationType) {
    if (!annotationType.isAnnotationPresent(Qualifier.class)) {
        throw new IllegalArgumentException("Annotation is not a qualifier: " + annotationType);
    }
}
 
Example #30
Source File: BeanManagerImpl.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isQualifier(Class<? extends Annotation> annotationType) {
    // BeforeBeanDiscovery.addQualifier() and equivalents are not supported
    return annotationType.isAnnotationPresent(Qualifier.class);
}