javax.inject.Scope Java Examples

The following examples show how to use javax.inject.Scope. 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: AbstractJerseyInstaller.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
/**
 * Checks scope annotation presence directly on bean. Base classes are not checked as scope is not
 * inheritable.
 *
 * @param type      bean type
 * @param hkManaged true if bean is going to be managed by hk, false for guice management
 * @return true if scope annotation found, false otherwise
 */
private boolean hasScopeAnnotation(final Class<?> type, final boolean hkManaged) {
    boolean found = false;
    for (Annotation ann : type.getAnnotations()) {
        final Class<? extends Annotation> annType = ann.annotationType();
        if (annType.isAnnotationPresent(Scope.class)) {
            found = true;
            break;
        }
        // guice has special marker annotation
        if (!hkManaged && annType.isAnnotationPresent(ScopeAnnotation.class)) {
            found = true;
            break;
        }
    }
    return found;
}
 
Example #2
Source File: MicronautBeanFactory.java    From micronaut-spring with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isPrototype(@Nonnull String name) throws NoSuchBeanDefinitionException {
    if (super.containsSingleton(name)) {
        return false;
    }

    final BeanDefinitionReference<?> definition = beanDefinitionMap.get(name);
    if (definition != null) {
        final AnnotationMetadata annotationMetadata = definition.getAnnotationMetadata();
        if (annotationMetadata.hasDeclaredStereotype(Prototype.class)) {
            return true;
        } else {
            final boolean hasScope = annotationMetadata.getAnnotationNamesByStereotype(Scope.class).isEmpty();
            return !hasScope;
        }
    }
    return false;
}
 
Example #3
Source File: ScopeExtractor.java    From Mortar-architect with MIT License 6 votes vote down vote up
/**
 * Find annotation that is itself annoted with @Scope
 * If there is one, it will be later applied on the generated component
 * Otherwise the component will be unscoped
 * Throw error if more than one scope annotation found
 */
private AnnotationMirror findScope() {
    AnnotationMirror annotationTypeMirror = null;

    for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) {
        Element annotationElement = annotationMirror.getAnnotationType().asElement();
        if (MoreElements.isAnnotationPresent(annotationElement, Scope.class)) {
            // already found one scope
            if (annotationTypeMirror != null) {
                errors.addInvalid("Several dagger scopes on same element are not allowed");
                continue;
            }

            annotationTypeMirror = annotationMirror;
        }
    }

    return annotationTypeMirror;
}
 
Example #4
Source File: InjectorBuilderImpl.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
@Override
public BindingBuilderImpl<T> scope(Class<? extends Annotation> scopeType)
{
  Objects.requireNonNull(scopeType);

  if (! scopeType.isAnnotationPresent(Scope.class)) {
    throw error("'@{0}' is an invalid scope type because it is not annotated with @Scope",
                scopeType.getSimpleName());
  }

  if (_scopeMap.get(scopeType) == null) {
    throw error("'@{0}' is an unsupported scope. Only @Singleton and @Factory are supported.",
                scopeType.getSimpleName());

  }

  _scopeType = scopeType;

  return this;
}
 
Example #5
Source File: QualifierCacheTests.java    From Spork with Apache License 2.0 6 votes vote down vote up
@Test
public void annotationWithoutValueMethod() {
	Annotation annotation = Singleton.class.getAnnotation(Scope.class);
	cache.getQualifier(annotation);

	InOrder inOrder = inOrder(lock, cache);

	// initial call
	inOrder.verify(cache).getQualifier(annotation);

	// internal thread safe method lookup
	inOrder.verify(cache).getValueMethodThreadSafe(Scope.class);
	inOrder.verify(lock).lock();
	inOrder.verify(cache).getValueMethod(Scope.class);
	inOrder.verify(lock).unlock();
	// no value Method found, so no invocation needed

	inOrder.verifyNoMoreInteractions();
	verifyZeroInteractions(cache);
	assertThat(bindActionMap.size(), is(1));
}
 
Example #6
Source File: InjectorImpl.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Finds the scope for a bean producing declaration, either a method or
 * a type.
 */
private <T> InjectScope<T> findScope(AnnotatedElement annElement)
{
  for (Annotation ann : annElement.getAnnotations()) {
    Class<? extends Annotation> annType = ann.annotationType();

    if (annType.isAnnotationPresent(Scope.class)) {
      Supplier<InjectScope<T>> scopeGen = (Supplier) _scopeMap.get(annType);

      if (scopeGen != null) {
        return scopeGen.get();
      }
      else {
        log.fine(L.l("@{0} is an unknown scope", annType.getSimpleName()));
      }
    }
  }

  return new InjectScopeFactory<>();
}
 
Example #7
Source File: FactoryProcessor.java    From toothpick with Apache License 2.0 6 votes vote down vote up
private void checkScopeAnnotationValidity(TypeElement annotation) {
  if (annotation.getAnnotation(Scope.class) == null) {
    error(
        annotation,
        "Scope Annotation %s does not contain Scope annotation.",
        annotation.getQualifiedName());
    return;
  }

  Retention retention = annotation.getAnnotation(Retention.class);
  if (retention == null || retention.value() != RetentionPolicy.RUNTIME) {
    error(
        annotation,
        "Scope Annotation %s does not have RUNTIME retention policy.",
        annotation.getQualifiedName());
  }
}
 
Example #8
Source File: Reflection.java    From dagger-reflect with Apache License 2.0 6 votes vote down vote up
/**
 * Finds scoping annotations that aren't {@link Reusable}. Reusable is ignored since it is a best
 * effort optimization and isn't a real scoping annotation.
 *
 * @param annotations The set of annotations to parse for scoping annotations.
 * @return All annotations with Scope or an empty set if none are found.
 */
static Set<Annotation> findScopes(Annotation[] annotations) {
  Set<Annotation> scopes = null;
  for (Annotation annotation : annotations) {
    // Reusable is ignored.
    if (annotation.annotationType() == Reusable.class) {
      continue;
    }
    if (annotation.annotationType().getAnnotation(Scope.class) != null) {
      if (scopes == null) {
        scopes = new LinkedHashSet<>();
      }
      scopes.add(annotation);
    }
  }
  return scopes != null ? scopes : Collections.emptySet();
}
 
Example #9
Source File: FactoryProcessor.java    From toothpick with Apache License 2.0 6 votes vote down vote up
/**
 * Lookup {@link javax.inject.Scope} annotated annotations to provide the name of the scope the
 * {@code typeElement} belongs to. The method logs an error if the {@code typeElement} has
 * multiple scope annotations.
 *
 * @param typeElement the element for which a scope is to be found.
 * @return the scope of this {@code typeElement} or {@code null} if it has no scope annotations.
 */
private String getScopeName(TypeElement typeElement) {
  String scopeName = null;
  boolean hasScopeAnnotation = false;
  for (AnnotationMirror annotationMirror : typeElement.getAnnotationMirrors()) {
    TypeElement annotationTypeElement =
        (TypeElement) annotationMirror.getAnnotationType().asElement();
    boolean isSingletonAnnotation =
        annotationTypeElement.getQualifiedName().contentEquals("javax.inject.Singleton");
    if (!isSingletonAnnotation && annotationTypeElement.getAnnotation(Scope.class) != null) {
      checkScopeAnnotationValidity(annotationTypeElement);
      if (scopeName != null) {
        error(typeElement, "Only one @Scope qualified annotation is allowed : %s", scopeName);
      }
      scopeName = annotationTypeElement.getQualifiedName().toString();
    }
    if (isSingletonAnnotation) {
      hasScopeAnnotation = true;
    }
  }
  if (hasScopeAnnotation && scopeName == null) {
    scopeName = "javax.inject.Singleton";
  }
  return scopeName;
}
 
Example #10
Source File: AnnotationsTests.java    From Spork with Apache License 2.0 5 votes vote down vote up
@Test
public void methodArgumentScopeMissingTest() throws NoSuchMethodException {
	Method method = Testable.class.getDeclaredMethod("scopedMethodArgumentsMissing", Object.class);
	Annotation[] annotations = method.getParameterAnnotations()[0];
	Annotation namedAnnotation = Annotations.findAnnotationAnnotatedWith(Scope.class, annotations);

	assertThat(namedAnnotation, is(nullValue()));
}
 
Example #11
Source File: ComponentExtractor.java    From Auto-Dagger2 with MIT License 5 votes vote down vote up
private AnnotationMirror findScope(Element element) {
    List<AnnotationMirror> annotationMirrors = ExtractorUtil.findAnnotatedAnnotation(element, Scope.class);
    if (annotationMirrors.isEmpty()) {
        return null;
    }

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

    return annotationMirrors.get(0);
}
 
Example #12
Source File: SubcomponentExtractor.java    From Auto-Dagger2 with MIT License 5 votes vote down vote up
/**
 * Find annotation that is itself annoted with @Scope
 * If there is one, it will be later applied on the generated component
 * Otherwise the component will be unscoped
 * Throw error if more than one scope annotation found
 */
private AnnotationMirror findScope() {
    List<AnnotationMirror> annotationMirrors = ExtractorUtil.findAnnotatedAnnotation(element, Scope.class);
    if (annotationMirrors.isEmpty()) {
        return null;
    }

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

    return annotationMirrors.get(0);
}
 
Example #13
Source File: InjectorBuilderImpl.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
private Class<? extends Annotation> scope(Method method)
{
  for (Annotation ann : method.getAnnotations()) {
    if (ann.annotationType().isAnnotationPresent(Scope.class)) {
      return ann.annotationType();
    }
  }

  return Singleton.class;
}
 
Example #14
Source File: FactoryProcessor.java    From toothpick with Apache License 2.0 5 votes vote down vote up
private void createFactoriesForClassesAnnotatedWithScopeAnnotations(
    RoundEnvironment roundEnv, Set<? extends TypeElement> annotations) {
  for (TypeElement annotation : annotations) {
    if (annotation.getAnnotation(Scope.class) != null) {
      checkScopeAnnotationValidity(annotation);
      createFactoriesForClassesAnnotatedWith(roundEnv, annotation);
    }
  }
}
 
Example #15
Source File: AnnotationsTests.java    From Spork with Apache License 2.0 5 votes vote down vote up
@Test
public void methodArgumentScopeTest() throws NoSuchMethodException {
	Method method = Testable.class.getDeclaredMethod("scopedMethodArguments", Object.class);
	Annotation[] annotations = method.getParameterAnnotations()[0];
	Annotation namedAnnotation = Annotations.findAnnotationAnnotatedWith(Scope.class, annotations);

	assertThat(namedAnnotation, allOf(notNullValue(), annotationOfType(Singleton.class)));
}
 
Example #16
Source File: AnnotationsTests.java    From Spork with Apache License 2.0 5 votes vote down vote up
@Test
public void methodScopeTest() throws NoSuchMethodException {
	Method method = Testable.class.getDeclaredMethod("scopedMethod");
	Annotation namedAnnotation = Annotations.findAnnotationAnnotatedWith(Scope.class, method);

	assertThat(namedAnnotation, allOf(notNullValue(), annotationOfType(Singleton.class)));
}
 
Example #17
Source File: AnnotationsTests.java    From Spork with Apache License 2.0 5 votes vote down vote up
@Test
public void fieldScopeTest() throws NoSuchFieldException {
	Field field = Testable.class.getDeclaredField("scopedField");
	Annotation namedAnnotation = Annotations.findAnnotationAnnotatedWith(Scope.class, field);

	assertThat(namedAnnotation, allOf(notNullValue(), annotationOfType(Singleton.class)));
}
 
Example #18
Source File: QualifierCacheTests.java    From Spork with Apache License 2.0 5 votes vote down vote up
@Test
public void methodCaching() {
	Annotation annotation = Singleton.class.getAnnotation(Scope.class);
	// call twice - should cache once
	cache.getQualifier(annotation);
	cache.getQualifier(annotation);

	assertThat(bindActionMap.size(), is(1));
}
 
Example #19
Source File: MockBean.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
private static Set<Annotation> getScopes(AnnotatedElement element) {
    Set<Annotation> scopes = new HashSet<>();
    for (Annotation annotation : element.getAnnotations()) {
        if (annotation.annotationType().isAnnotationPresent(Scope.class) || annotation.annotationType().isAnnotationPresent(NormalScope.class)) {
            scopes.add(annotation);
        }
    }
    return scopes;
}
 
Example #20
Source File: ExcludedBeansExtension.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
<T> void excludeBeans(@Observes @WithAnnotations({Scope.class, NormalScope.class}) ProcessAnnotatedType<T> pat) {

        if (excludedBeanClasses.contains(pat.getAnnotatedType().getJavaClass())) {
            pat.veto();
            return;
        }

        Set<Type> typeClosure = pat.getAnnotatedType().getTypeClosure();
        for (Type excludedBeanType : excludedBeanTypes) {
            if (typeClosure.contains(excludedBeanType)) {
                pat.veto();
                return;
            }
        }
    }
 
Example #21
Source File: ObjectGraphNode.java    From Spork with Apache License 2.0 4 votes vote down vote up
ObjectGraphNode(InjectSignature injectSignature, Object parent, Method method) {
	this.injectSignature = injectSignature;
	this.parent = parent;
	this.method = method;
	this.scopeAnnotation = Annotations.findAnnotationAnnotatedWith(Scope.class, method); // TODO: cache?
}
 
Example #22
Source File: InjectionAnnotations.java    From dagger2-sample with Apache License 2.0 4 votes vote down vote up
static ImmutableSet<? extends AnnotationMirror> getScopes(Element element) {
  return AnnotationMirrors.getAnnotatedAnnotations(element, Scope.class);
}
 
Example #23
Source File: ArcContainerImpl.java    From quarkus with Apache License 2.0 4 votes vote down vote up
boolean isScope(Class<? extends Annotation> annotationType) {
    if (annotationType.isAnnotationPresent(Scope.class) || annotationType.isAnnotationPresent(NormalScope.class)) {
        return true;
    }
    return contexts.stream().map(InjectableContext::getScope).filter(annotationType::equals).findAny().isPresent();
}