Class BeanInstantiator<T>

java.lang.Object
org.apache.juneau.commons.inject.BeanInstantiator<T>
Type Parameters:
T - The bean type being created.

public class BeanInstantiator<T> extends Object
Utility class for creating beans through constructors, creator methods, and builders.

Uses a BeanStore to find available ways to construct beans via injection of beans from the store.

This class is instantiated through the following method:

Example:

// Bean with builder pattern public class MyBean { private final String value; private MyBean(String value) { this.value = value; } public static Builder create() { return new Builder(); } public static class Builder { private String value; public Builder value(String value) { this.value = value; return this; } public MyBean build() { return new MyBean(value); } } // Builder with @Inject on build() method public class MyBean2 { private final String value; private final MyDependency dependency; private MyBean2(String value, MyDependency dependency) { this.value = value; this.dependency = dependency; } public static class Builder { private String value; public Builder value(String value) { this.value = value; return this; } @Inject public MyBean2 build(MyDependency dependency) { return new MyBean2(value, dependency); } } } } // Create bean using BeanInstantiator MyBean bean = BeanInstantiator .of(MyBean.class, myBeanStore) .run();

Bean Creation Order:

The creator attempts to instantiate beans in the following order:

  1. Using a Builder (if a builder is found or specified):
    1. Calls a build()/create()/get() method on the builder that returns the bean type.
      • The method is required - if no such method exists, bean creation fails.
      • If the method has @Inject or @Autowired annotation, its parameters are resolved from the bean store.
      • If the method does not have @Inject annotation, it must have no parameters.
  2. Without a Builder:
    1. Calls a static no-arg getInstance() method on the bean class.
    2. Calls a public constructor with parameters that can be resolved from the bean store.
    3. Falls back to a protected constructor with parameters that can be resolved from the bean store.
    4. Falls back to a package-private constructor with parameters that can be resolved from the bean store. Private constructors are deliberately excluded.
Builder Detection:

Builders are detected in the following priority order:

  1. Explicitly set via BeanInstantiator.Builder.builder(Object) or BeanInstantiator.Builder.builder(Class).
  2. @Builder annotation on the bean subtype.
  3. @Builder annotation on the bean type.
  4. Auto-detection:
Dependency Injection:

Both builder instances and the final bean have automatic dependency injection performed via ClassInfo.inject(Object, BeanStore), which processes @Inject and @Autowired annotations on fields and methods.

This means that after a bean is created, all of its fields and methods annotated with @Inject or @Autowired will automatically be populated with beans from the bean store.

Caching:

By default, each call to run() creates a new bean instance. To enable caching, call BeanInstantiator.Builder.cached(). When caching is enabled, bean instances are cached using Memoizer, so multiple calls to run() will return the same instance unless reset() is called or configuration changes. Explicit implementations set via BeanInstantiator.Builder.impl(Object) and explicit builder instances set via BeanInstantiator.Builder.builder(Object) are preserved across resets.

Thread Safety:

Configuration is performed on the inner BeanInstantiator.Builder which is not thread-safe. Configure on a single thread, then call BeanInstantiator.Builder.build() to produce an immutable BeanInstantiator that is safe for shared concurrent use. The BeanInstantiator.Builder.run() shorthand is equivalent to build().run() and is appropriate for one-shot bean creation from a single thread.

Notes:
  • Builders must have a build(), create(), or get() method that returns the bean type. This method is required - constructors accepting builders are no longer supported.
  • The builder's build()/create()/get() method may have @Inject or @Autowired annotation to allow dependency injection of parameters from the bean store.
  • If the builder's build()/create()/get() method does not have @Inject annotation, it must have no parameters.
  • All constructors and methods except Optional and List parameters must have beans available in the store.
  • If multiple constructors/methods are found, the one with the most matching parameters is used.
  • Deprecated and @BeanIgnore-annotated methods/constructors are ignored.
See Also:
  • Field Details

  • Method Details

    • of

      public static <T> BeanInstantiator.Builder<T> of(Class<T> beanType)
      Creates a new bean creator builder.
      Type Parameters:
      T - The bean type to create.
      Parameters:
      beanType - The bean type to create. Must not be null.
      Returns:
      A new bean creator builder.
    • of

      public static <T> BeanInstantiator.Builder<T> of(Class<T> beanType, BeanStore parentStore)
      Creates a new bean creator builder with a parent bean store.
      Type Parameters:
      T - The bean type to create.
      Parameters:
      beanType - The bean type to create. Must not be null.
      parentStore - The parent bean store to use for resolving dependencies. Can be null (the internal bean store then has no parent fallback).
      Returns:
      A new bean creator builder.
    • of

      public static <T> BeanInstantiator.Builder<T> of(Class<T> beanType, BeanStore parentStore, String name, Object enclosingInstance)
      Creates a new bean creator builder with a parent bean store, name, and enclosing instance.
      Type Parameters:
      T - The bean type to create.
      Parameters:
      beanType - The bean type to create. Must not be null.
      parentStore - The parent bean store to use for resolving dependencies. Can be null (the internal bean store then has no parent fallback).
      name - The bean name. Can be null for unnamed beans.
      enclosingInstance - The enclosing instance object. Can be null (the outer-instance skip rule is then never applied).
      Returns:
      A new bean creator builder.
    • createOrNull

      public static <T> T createOrNull(Class<T> beanType)
      Instantiates a bean of the given type, or returns null if the type is null or instantiation fails.

      Shorthand for the common pattern:

      cls == null ? null : BeanInstantiator.of(cls).fallback(() -> null).run()

      Type Parameters:
      T - The bean type to create.
      Parameters:
      beanType - The bean type to create. Can be null.
      Returns:
      A new bean instance, or null if the type is null or instantiation fails.
    • optionalOf

      public static <T> Optional<T> optionalOf(Class<T> beanType)
      Instantiates a bean of the given type and wraps it in an Optional, or returns Optional.empty() if the type is null or instantiation fails.

      Shorthand for the common pattern:

      cls == null ? Optional.empty() : BeanInstantiator.of(cls).asOptional()

      Type Parameters:
      T - The bean type to create.
      Parameters:
      beanType - The bean type to create. Can be null.
      Returns:
      An Optional containing the created bean, or Optional.empty() if the type is null or instantiation fails.
    • createOrDefault

      public static <T> T createOrDefault(Class<T> beanType, T defaultValue)
      Instantiates a bean of the given type, or returns a default value if the type is null.

      Shorthand for the common pattern:

      cls == null ? defaultValue : BeanInstantiator.of(cls).run()

      Type Parameters:
      T - The bean type to create.
      Parameters:
      beanType - The bean type to create. Can be null.
      defaultValue - The value to return if beanType is null. Can be null.
      Returns:
      A new bean instance, or defaultValue if the type is null.
    • run

      public T run()
      Creates the bean.

      After creating the bean, this method automatically injects dependencies into fields and methods annotated with @Inject or @Autowired using ClassInfo.inject(Object, BeanStore).

      Returns:
      A new bean with all dependencies injected.
      Throws:
      ExecutableException - if bean could not be created.
    • asOptional

      public Optional<T> asOptional()
      Attempts to create the bean, returning an Optional instead of throwing an exception on failure.
      Returns:
      An Optional containing the created bean, or Optional.empty() if creation failed.
    • asMemoizer

      public Memoizer<T> asMemoizer()
      Converts this creator into a memoizer.
      Returns:
      A resettable supplier that caches the created bean until reset.
    • asSupplier

      public Supplier<T> asSupplier()
      Converts this creator into a supplier.
      Returns:
      A supplier that returns the results of the run() method.
    • reset

      Resets the cached bean instance and the inner Builder's resolved memoizers.
      Returns:
      This object.
    • getName

      public String getName()
      Returns the name of the bean being created.
      Returns:
      The bean name, or null if not set.
    • getBeanSubType

      Returns the bean subtype class info if specified, or the normal bean type if not.
      Returns:
      The bean subtype class info, or the bean type class info if no subtype was specified.
    • getBeanSubTypes

      Returns the list of bean subtype classes, including the bean subtype, bean type, and all classes in between.
      Returns:
      A list of bean subtype class info objects, never null.
    • getBuilder

      public <B> Optional<B> getBuilder()
      Returns the builder instance if one has been created or specified.
      Type Parameters:
      B - The builder type.
      Returns:
      The builder instance wrapped in an Optional, or an empty optional if no builder exists.
    • getBuilderType

      Returns the builder type class info determined by builder type detection.
      Returns:
      The builder type class info, or null if no builder type was determined.
    • getBuilderTypes

      Returns the list of builder types, including the primary builder type and any builder types found in the builder's parent hierarchy.
      Returns:
      A list of builder type class info objects, never null.
    • getDebugLog

      public List<String> getDebugLog()
      Returns an unmodifiable list of debug log entries from the last bean creation attempt.
      Returns:
      An unmodifiable list of debug log entries.