下面列出了com.google.inject.BindingAnnotation#javax.inject.Qualifier 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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());
}
}
@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());
}
}
/**
* 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);
}
/**
* 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));
}
}
@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());
}
}
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;
}
/**
* 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;
}
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);
}
}
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;
}
/**
* 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));
}
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;
}
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]);
}
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;
}
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 + ")";
}
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);
}
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();
}
boolean isQualifier(Annotation ann)
{
Class<?> annType = ann.annotationType();
if (annType.isAnnotationPresent(Qualifier.class)) {
return true;
}
return _qualifierSet.contains(annType);
}
private boolean isProduces(Annotation []anns)
{
if (anns == null) {
return false;
}
for (Annotation ann : anns) {
if (ann.annotationType().isAnnotationPresent(Qualifier.class)) {
return true;
}
}
return false;
}
@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);
}
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;
}
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;
}
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);
}
private static Annotation findFirstQualifierInAnnotations(Annotation[] annotations) {
if (annotations != null) {
for (Annotation a : annotations) {
if (a.annotationType().isAnnotationPresent(Qualifier.class)) {
return a;
}
}
}
return null;
}
/**
* 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();
}
/**
* 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));
}
private Optional<Annotation> findQualifier(Class<? extends T> target) {
return Annotations.on(target)
.traversingSuperclasses()
.traversingInterfaces()
.findAll()
.filter(AnnotationPredicates.annotationAnnotatedWith(Qualifier.class, false))
.findFirst();
}
private static void verifyQualifier(Class<? extends Annotation> annotationType) {
if (!annotationType.isAnnotationPresent(Qualifier.class)) {
throw new IllegalArgumentException("Annotation is not a qualifier: " + annotationType);
}
}
@Override
public boolean isQualifier(Class<? extends Annotation> annotationType) {
// BeforeBeanDiscovery.addQualifier() and equivalents are not supported
return annotationType.isAnnotationPresent(Qualifier.class);
}
@SuppressWarnings("unchecked")
@Override
protected <T> T doGetBean(String name, Class<T> requiredType, Object[] args, boolean typeCheckOnly) throws BeansException {
if (beanExcludes.contains(requiredType)) {
throw new NoSuchBeanDefinitionException(name);
}
if (super.containsSingleton(name)) {
final Object o = super.getSingleton(name);
if (requiredType == null || requiredType.isInstance(o)) {
return (T) o;
}
}
BeanDefinitionReference<?> reference = beanDefinitionMap.get(name);
if (reference == null) {
// by name, with no type lookups
final BeanDefinitionReference<?> ref = beanDefinitionsByName.get(name);
if (ref != null) {
if (requiredType != null) {
if (requiredType.isAssignableFrom(ref.getBeanType())) {
reference = ref;
}
} else {
reference = ref;
}
}
}
if (reference != null) {
final BeanDefinition<?> definition = reference.load(beanContext);
if (definition.isEnabled(beanContext)) {
if (requiredType == null) {
requiredType = (Class<T>) definition.getBeanType();
}
io.micronaut.context.Qualifier<T> q = (io.micronaut.context.Qualifier<T>) definition.getValue(Named.class, String.class)
.map((String n) -> {
if (Primary.class.getName().equals(n)) {
return n;
}
return Qualifiers.byName(n);
})
.orElseGet(() -> {
if (definition.hasDeclaredStereotype(Primary.class)) {
return null;
}
final Class annotationType = definition.getAnnotationTypeByStereotype(Qualifier.class).orElse(null);
if (annotationType != null) {
return Qualifiers.byAnnotation(definition, annotationType);
}
return null;
}
);
if (q != null) {
return beanContext.getBean(requiredType, q);
} else {
return beanContext.getBean(requiredType);
}
}
}
if (requiredType != null) {
try {
return beanContext.getBean(requiredType, Qualifiers.byName(name));
} catch (NoSuchBeanException e) {
throw new NoSuchBeanDefinitionException(name);
}
} else {
throw new NoSuchBeanDefinitionException(name);
}
}
private static boolean isBeanParameterAnnotation(Annotation ann) {
return isAnnotated(ann.annotationType(), Qualifier.class);
}