Class BeanInstantiator.Builder<T>
- Type Parameters:
T- The bean type being created.
- Enclosing class:
- BeanInstantiator<T>
BeanInstantiator.
Holds all mutable configuration. Configure on a single thread, then call build() to obtain
an immutable BeanInstantiator suitable for shared concurrent use. Most call sites use the
run() shorthand which is equivalent to build().run().
Thread Safety:
Builder instances are not thread-safe. Configure on one thread, then either call build()
to produce a thread-safe immutable BeanInstantiator, or call run() to one-shot create a
bean from a single thread.
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescription<T2> T2Adds a bean to the internal bean store and returns it.<T2> BeanInstantiator.Builder<T>Adds a bean to the internal bean store.<T2> BeanInstantiator.Builder<T>Adds a named bean to the internal bean store.Converts this creator into a memoizer.Attempts to create the bean, returning anOptionalinstead of throwing an exception on failure.Converts this creator into a supplier.Enables auto-wiring of bean store entries into matching setter methods on the builder.build()Compiles this builder into aBeanInstantiator.Specifies the builder type to use for creating the bean.Specifies an existing builder instance to use for creating the bean.builderClassNames(String... names) Specifies custom class names to look for when auto-detecting builder inner classes.builderInitializer(Consumer<Object> initializer) Registers a callback that is invoked on the builder instance beforebuild()is called.builderMethodNames(String... names) Specifies custom method names to look for when auto-detecting builder factory methods.buildMethodNames(String... names) Specifies custom method names to look for when calling build methods on builder instances.cached()Enables caching mode.copy()Returns a copy of this builder with the same configuration.debug()Enables debug mode to track the bean creation process.description(String value) Sets a human-readable description used in log entries and error messages.Treat anullreturn value from a static factory method as a deliberate "abstain" signal.factoryMethodNames(String... names) Specifies custom static factory method names to look for when creating the bean.Specifies a fallback supplier to use if bean creation fails.protected ClassInfoReturns the bean subtype class info if specified, or the normal bean type if not.Returns the list of bean subtype classes, including the bean subtype, bean type, and all classes in between.<B> Optional<B>Returns the builder instance if one has been created or specified.protected ClassInfoReturns the builder type class info determined byfindBuilderType().Returns the list of builder types, including the primary builder type and any builder types found in the builder's parent hierarchy.Returns an unmodifiable list of debug log entries from the last bean creation attempt.getName()Returns the name of the bean being created.Specifies an existing bean implementation to use instead of creating a new instance.Enables@Inject/@Autowiredfield and method injection on the builder instance.Disables builder-based bean creation entirely.or(BeanInstantiator.Builder<? extends T> alternative) Registers an alternativeBeanInstantiator.Builderto consult if this builder fails to create the bean.postCreateHook(Consumer<T> hook) Registers a post-creation hook to run after the bean is created.Prefer a zero-argument constructor when one exists, instead of injecting via the longest constructor.reset()Resets the builder, builderType, and beanImpl suppliers.run()Shortcut forbuild().run().scope(BeanInstantiator.Scope value) Sets the lifecycle scope of the bean being created.silent()Suppresses warning-level log output from this builder.Specifies a subclass of the bean type to create.Specifies a subclass of the bean type to create, via aClassInforeference.Registers a post-creation validator.wrap(UnaryOperator<T> wrapper) Registers a transformation to apply to the created bean before it is returned.
-
Constructor Details
-
Builder
Constructor.- Parameters:
beanType- The bean type being created. Must not benull .parentStore- The parent bean store to use for resolving dependencies. Can benull (the internal bean store then has no parent fallback).name- The bean name. Can benull for unnamed beans.enclosingInstance- The enclosing instance object. Can benull (the outer-instance skip rule is then never applied).
-
-
Method Details
-
add
Adds a bean to the internal bean store and returns it.- Type Parameters:
T2- The bean type.- Parameters:
type- The bean type. Must not benull .bean- The bean instance. Can benull (stored as an explicitnull binding, distinct from no binding at all).- Returns:
- The bean that was added.
-
addBean
Adds a bean to the internal bean store.- Type Parameters:
T2- The bean type.- Parameters:
type- The bean type. Must not benull .bean- The bean instance. Can benull (stored as an explicitnull binding, distinct from no binding at all).- Returns:
- This object.
-
addBean
Adds a named bean to the internal bean store.- Type Parameters:
T2- The bean type.- Parameters:
type- The bean type. Must not benull .bean- The bean instance. Can benull (stored as an explicitnull binding, distinct from no binding at all).name- The bean name. Can benull for unnamed beans.- Returns:
- This object.
-
asOptional
Attempts to create the bean, returning anOptionalinstead of throwing an exception on failure.This is a non-throwing variant of
run()that wraps the result in anOptional. If bean creation fails for any reason (missing dependencies, abstract class, interface, no matching constructor, etc.), this method returnsOptional.empty()instead of throwingExecutableException.This method is useful when bean creation failure is expected and should not be treated as exceptional, such as when implementing optional features or trying multiple creation strategies.
Notes:
- Unlike
run(), this method catchesExecutableExceptionand returns empty. - If a fallback is registered via
fallback(Supplier), it will be used before returning empty, so this method will only return empty if both normal creation AND fallback fail. - The created bean is cached via
Memoizer, so subsequent calls return the same instance unlessreset()is called or configuration changes. - Post-creation hooks are still executed if creation succeeds.
- Other exceptions (e.g., from post-creation hooks or fallback suppliers) are NOT caught and will propagate to the caller.
Example:
// Try to create, use default if it fails MyBeanbean = BeanInstantiator .of (MyBean.class ,myBeanStore ) .asOptional() .orElse(new DefaultMyBean());// Chain multiple creation attempts MyServiceservice = BeanInstantiator.of (AdvancedService.class ,store ) .asOptional() .or(() -> BeanInstantiator.of (BasicService.class ,store ) .asOptional()) .orElseGet(() ->new FallbackService());// Check if optional feature is available Optional<OptionalFeature>feature = BeanInstantiator .of (OptionalFeature.class ,store ) .asOptional();if (feature .isPresent()) {feature .get().enable(); }- Returns:
- An
Optionalcontaining the created bean, orOptional.empty()if creation failed.
- Unlike
-
asMemoizer
Converts this creator into a memoizer.A
Memoizercaches the result of the firstMemoizer.get()call and returns that cached value for subsequent calls. TheMemoizer.reset()method can be used to clear the cache, forcing the bean to be recreated on the next get() call.This is particularly useful when the bean store contents change and you want to recreate the bean with updated dependencies.
Notes:
- The returned
Memoizeris thread-safe. - Each call to
Memoizer.get()after a reset() will invokerun(), which may trigger dependency injection and post-creation hooks. - The memoizer inherits all Optional-like methods from
NullableSupplier.
Example:
// Create a memoizer for a bean with dependencies BeanStorestore =new BasicBeanStore(null );store .addBean(String.class ,"initial" ); Memoizer<MyBean>supplier = BeanInstantiator .of (MyBean.class ,store ) .asMemoizer();// First call creates and caches the bean MyBeanbean1 =supplier .get();// Subsequent calls return the cached bean MyBeanbean2 =supplier .get();assertSame (bean1 ,bean2 );// Update the bean store store .addBean(String.class ,"updated" );// Reset forces recreation with updated dependencies supplier .reset(); MyBeanbean3 =supplier .get();assertNotSame (bean1 ,bean3 );// New instance with updated deps - Returns:
- A resettable supplier that caches the created bean until reset.
- The returned
-
asSupplier
Converts this creator into a supplier.- Returns:
- A supplier that returns the results of the
run()method.
-
type
Specifies a subclass of the bean type to create.This allows you to create a specific implementation when the bean type is an interface, abstract class, or when you want to instantiate a customized subclass of a concrete class.
- Parameters:
value- The subclass type to create. Cannot benull . Must be a subclass ofbeanType.- Returns:
- This object.
- Throws:
IllegalArgumentException- If value is not a subclass ofbeanType.
-
type
Specifies a subclass of the bean type to create, via aClassInforeference.Convenience overload of
type(Class)that acceptsClassInfo(or any subtype such asClassMeta). The underlying class is extracted viaClassInfo.inner()and the subtype-relationship check happens at runtime.- Parameters:
value- The subclass type to create. Cannot benull .- Returns:
- This object.
- Throws:
IllegalArgumentException- Ifvalueisnull or its underlying class is not a subclass ofbeanType.
-
builder
Specifies the builder type to use for creating the bean.This method triggers builder type detection and instantiation for the specified type.
The builder type must be valid, meaning it must have a
build() ,create() , orget() method that returns the bean type (or a parent of the bean type). The method may have@Inject or@Autowired annotation to allow injected parameters; otherwise, it must have no parameters.If the builder type is invalid (does not have a valid build method), this method throws an
IllegalArgumentException.The builder will be instantiated by looking for:
- A static
create() orbuilder() method that returns the builder type. - A public constructor on the builder type with parameters that can be resolved from the bean store.
- A protected constructor on the builder type with parameters that can be resolved from the bean store.
- A package-private constructor on the builder type with parameters that can be resolved from the bean store. Private constructors are deliberately excluded.
- Parameters:
value- The builder type. Cannot benull .- Returns:
- This object.
- Throws:
IllegalArgumentException- If the builder type is invalid (does not have a valid build/create/get method).
- A static
-
builder
Specifies an existing builder instance to use for creating the bean.The builder instance's class must be a valid builder type, meaning it must have a
build() ,create() , orget() method that returns the bean type (or a parent of the bean type). The method may have@Inject or@Autowired annotation to allow injected parameters; otherwise, it must have no parameters.If the builder instance's class is invalid (does not have a valid build method), this method throws an
IllegalArgumentException.Notes:
- When specified, the builder type detection is bypassed.
- The builder will be used to create the bean via:
- A
build() /create() /get() method on the builder (required). The method may have@Inject annotation to allow injected parameters.
- A
- The explicit builder instance is preserved even when
reset()is called, unlike cached results from suppliers.
- Parameters:
value- The builder instance. Cannot benull .- Returns:
- This object.
- Throws:
IllegalArgumentException- If the builder instance's class is invalid (does not have a valid build/create/get method).
-
builderClassNames
Specifies custom class names to look for when auto-detecting builder inner classes.By default,
BeanInstantiatorlooks for inner classes named"Builder". This method allows you to specify alternative class names.Notes:
- Inner builder classes must be public, static, and pass builder validation (have a build/create/get method or be accepted by a bean constructor).
- If multiple inner classes match, the first valid one found will be used.
- This only affects inner class detection. It does not affect builders specified via
builder(Class),builder(Object), or the@Builderannotation. - Calling this method replaces the default builder class names.
Example:
// Support alternative builder class naming conventions MyBeanbean = BeanInstantiator .of (MyBean.class ,myBeanStore ) .builderClassNames("BuilderImpl" ,"Factory" ) .run();- Parameters:
names- The builder class names to look for. Cannot benull or containnull elements.- Returns:
- This object.
-
builderMethodNames
Specifies custom method names to look for when auto-detecting builder factory methods.By default,
BeanInstantiatorlooks for static methods named"create"or"builder"that return a builder type. This method allows you to specify alternative method names.Notes:
- Builder factory methods must be public, static, non-deprecated, and return a builder type (not the bean type itself).
- If multiple builder factory methods match, the one with the most parameters that can be resolved from the bean store will be used.
- This affects both builder type detection and builder instance creation.
- Calling this method replaces the default builder method names.
Example:
// Support alternative builder factory method naming conventions MyBeanbean = BeanInstantiator .of (MyBean.class ) .builderMethodNames("newBuilder" ,"instance" ) .run();- Parameters:
names- The builder factory method names to look for. Cannot benull or containnull elements.- Returns:
- This object.
-
buildMethodNames
Specifies custom method names to look for when calling build methods on builder instances.By default,
BeanInstantiatorlooks for instance methods named"build","create", or"get"on the builder that return the bean type. This method allows you to specify alternative method names.Notes:
- Build methods must be public, non-static, non-deprecated, and return the bean type (or a parent type of the bean type).
- If the method has
@Injector@Autowiredannotation, its parameters are resolved from the bean store. - If the method does not have
@Injectannotation, it must have no parameters. - Calling this method replaces the default build method names.
Example:
// Support alternative build method naming conventions MyBeanbean = BeanInstantiator .of (MyBean.class ) .buildMethodNames("execute" ,"make" ) .run();- Parameters:
names- The build method names to look for. Cannot benull or containnull elements.- Returns:
- This object.
-
cached
Enables caching mode.When caching mode is enabled, bean instances are cached using
Memoizer, so multiple calls torun()will return the same instance unlessreset()is called or configuration changes.When caching mode is disabled (the default), each call to
run()will create a new bean instance by callingfindBeanImpl()directly.Example:
// Enable caching mode - same instance returned on each run() var creator = BeanInstantiator .of (MyBean.class ) .cached (); MyBeanbean1 =creator .run (); MyBeanbean2 =creator .run ();// bean1 and bean2 are the same instance - Returns:
- This object.
-
factoryAbstainOnNull
Treat anullreturn value from a static factory method as a deliberate "abstain" signal.By default, when a static factory method (one of
factoryMethodNames(String...)) matches and is invoked, but returnsnull,run()falls through to constructor lookup as if the factory method weren't there. This works well when the factory method is just an alternate construction path.Some factory-method patterns instead use a
nullreturn value as a deliberate "this implementation does not handle the input — try the next strategy" signal, expecting the caller to interpret thenullas a definitive answer. The classic example is aRestOpArgsubclass whosestatic create(ParameterInfo)returnsnullwhen the parameter isn't annotated with the marker the subclass handles, so the caller can move on to the next subclass in the chain. Falling through to the (always-present) constructor in that case would silently materialize an arg that doesn't apply.When this flag is enabled, a
nullreturn from the matching factory method is propagated out ofrun()unchanged — constructor lookup is skipped. This matches legacyBeanCreatorsemantics for staticcreate()/builder()/getInstance()methods.Example:
// AttributeArg.create(ParameterInfo) returns null if @Attr is not present. // Without factoryAbstainOnNull, BeanInstantiator would then invoke the AttributeArg(ParameterInfo) // constructor and return a bogus instance. RestOpArgarg = BeanInstantiator .of (RestOpArg.class ,store ) .type(AttributeArg.class ) .factoryMethodNames("getInstance" ,"create" ) .factoryAbstainOnNull() .run();- Returns:
- This object.
-
preferZeroArgConstructor
Prefer a zero-argument constructor when one exists, instead of injecting via the longest constructor.By default,
BeanInstantiatorsorts public constructors by parameter count descending: the constructor with the most resolvable parameters wins, encouraging full constructor injection. This is the right default for most beans, but it doesn't fit every use case.The classic mismatch is parameterized container types like
TreeMap, which expose:TreeMap()TreeMap(Comparator)TreeMap(Map<? extends K,? extends V>)TreeMap(SortedMap)
Mapcopy-constructor — but thatMap<? extends K,? extends V>parameter doesn't satisfy v2 inject-collection auto-resolution (which only handlesMap<String,T>), so injection fails at runtime even thoughParameterInfo.canResolve(BeanStore, Object...)optimistically said yes. Callers that just want "give me a fresh empty container" should use this flag.When this flag is enabled, if
beanSubTypedeclares a public no-arg constructor, that constructor is used unconditionally and other constructors are ignored. This matches legacyBeanCreatorbehavior for the same use case (legacy filtered out the multi-arg ctors viahasAllParamsreturning false, since the legacy bean store didn't auto-resolve rawMap/Collectionparameter types).Example:
// Instantiating an arbitrary Map subclass — prefer the no-arg ctor over copy-ctors. Map<?,?>m = BeanInstantiator .of (Map.class ) .type(treeMapClass) .preferZeroArgConstructor() .run();- Returns:
- This object.
-
build
Compiles this builder into aBeanInstantiator.The returned instance exposes only run/read methods (no setters). The compiled instance shares its caching state with this builder so that
cached()memoization is consistent across both compiled and shorthand call paths.- Returns:
- A new
BeanInstantiatorbacked by this builder's configuration.
-
run
Shortcut forbuild().run().Most call sites do not store the
BeanInstantiatorand therefore call this shortcut. Repeated calls share caching with any compiledBeanInstantiatorproduced bybuild().- Returns:
- A new bean with all dependencies injected.
- Throws:
ExecutableException- if bean could not be created.
-
debug
Enables debug mode to track the bean creation process.When debug mode is enabled, the creator logs each step of the bean creation process to an internal list. This log can be retrieved via
getDebugLog()to understand which creation path was taken, why creation might have failed, or to troubleshoot unexpected behavior.Notes:
- Debug logs include: builder detection, factory method attempts, constructor attempts, dependency resolution, injection, hooks execution, validation, and fallback usage.
- The debug log is reset each time
run()orasOptional()is called. - Debug mode has minimal performance impact but should generally be disabled in production.
- The debug log is stored in memory and can be retrieved after bean creation.
- When caching is enabled via
cached(), the log reflects the first creation only (subsequent calls return the cached instance unlessreset()is called).
Example:
// Enable debug mode var creator = BeanInstantiator .of (MyBean.class ,store ) .debug(); MyBeanbean =creator .run();// Print debug log creator .getDebugLog().forEach(System.out ::println);- Returns:
- This object.
-
factoryMethodNames
Specifies custom static factory method names to look for when creating the bean.By default,
BeanInstantiatorlooks for a staticgetInstance()method when attempting to create beans without a builder. This method allows you to specify alternative factory method names to support non-standard naming conventions.Notes:
- Factory methods must be public, static, non-deprecated, and return the bean type.
- If multiple factory methods match, the one with the most parameters that can be resolved from the bean store will be used.
- Factory methods are attempted before constructors in the bean creation order.
- This setting only affects factory method detection; it does not affect builder detection.
- Calling this method replaces the default factory method names.
Example:
// Support multiple factory method naming conventions MyBeanbean = BeanInstantiator .of (MyBean.class ,myBeanStore ) .factoryMethodNames("of" ,"from" ,"create" ,"newInstance" ) .run();- Parameters:
names- The factory method names to look for. Cannot benull or containnull elements.- Returns:
- This object.
-
fallback
Specifies a fallback supplier to use if bean creation fails.When a fallback supplier is registered, if bean creation fails (throws
ExecutableException), instead of propagating the exception, the fallback supplier will be invoked to provide a default instance.This enables graceful degradation when bean creation cannot succeed, such as when optional features or dependencies are not available.
Notes:
- The fallback supplier is only invoked if bean creation fails. If bean creation succeeds normally, the fallback is never called.
- Fallbacks are checked after all normal creation attempts (builders, factory methods, constructors).
- The fallback-provided instance will have post-creation hooks executed on it.
- If the fallback is used, that instance is cached via
Memoizerand returned on subsequent calls unlessreset()is called or configuration changes. - Only one fallback can be registered. Subsequent calls to this method will replace the previous fallback.
- If the fallback supplier itself throws an exception, that exception will propagate to the caller.
- To use a pre-created instance as a fallback, wrap it in a supplier:
fallback(() -> myInstance) .
Example:
// Provide a default instance if creation fails MyServiceservice = BeanInstantiator .of (MyService.class ,myBeanStore ) .fallback(() ->new DefaultMyService()) .run();// Use a pre-created instance as fallback MyServicedefaultService =new DefaultMyService(); MyServiceservice2 = BeanInstantiator .of (MyService.class ,myBeanStore ) .fallback(() ->defaultService ) .run();- Parameters:
fallback- The fallback supplier. Cannot benull .- Returns:
- This object.
-
getBeanSubType
Returns the bean subtype class info if specified, or the normal bean type if not.If
type(Class)was called to specify a subtype, returns that subtype. Otherwise, returns the original bean type passed toBeanInstantiator.of(Class).- Returns:
- The bean subtype class info, or the bean type class info if no subtype was specified.
-
getName
Returns the name of the bean being created.Returns the name that was passed to
BeanInstantiator.of(Class, BeanStore, String, Object), ornull if no name was specified.- Returns:
- The bean name, or
null if not set.
-
getBeanSubTypes
Returns the list of bean subtype classes, including the bean subtype, bean type, and all classes in between.This method returns a list that starts with the bean subtype (if different from bean type) and includes all parent classes up to and including the bean type. If no subtype was specified, the list will contain only the bean type.
Example:
// If beanType is A and beanSubType is C (extends B extends A) // getBeanSubTypes() returns: [C, B, A] - Returns:
- A list of bean subtype class info objects, never
null .
-
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 byfindBuilderType().- 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.This method returns a list that includes the primary builder type and all builder types found by traversing the builder's parent hierarchy. This allows parent builders to be resolved as injectable types.
Example:
// Class A with builder class A {static class Builder { A create() {return new A(); } } }// Class B extends A with builder class Bextends A {static class Builderextends A.Builder { B create() {return new B(); } } }// When creating B, getBuilderTypes() returns: [B.Builder, A.Builder] - Returns:
- A list of builder type class info objects, never
null .
-
getDebugLog
Returns an unmodifiable list of debug log entries from the last bean creation attempt.This method returns the detailed log of steps taken during the most recent call to
run()orasOptional(). The log is only populated whendebug()mode is enabled.Notes:
- Returns an empty list if
debug()was not called or if no creation has been attempted. - The log is reset at the beginning of each
run()call. - Since
run()uses a cachedMemoizer, the log reflects only the first creation (subsequent calls return the cached instance unlessreset()is called). - The returned list is unmodifiable.
Example:
var creator = BeanInstantiator.of (MyBean.class ,store ) .debug();try {creator .run(); }catch (ExecutableExceptione ) {// Print debug log to understand why creation failed creator .getDebugLog().forEach(System.err ::println); }- Returns:
- An unmodifiable list of debug log entries.
- Returns an empty list if
-
impl
Specifies an existing bean implementation to use instead of creating a new instance.When specified, the bean creation logic is bypassed and this implementation is returned directly from
run(), after performing dependency injection on it.Notes:
- The bean implementation will still have its fields and methods injected via
ClassInfo.inject(Object, BeanStore). - This is useful when you want to provide a pre-configured instance but still benefit from dependency injection.
- The explicit implementation is preserved even when
reset()is called, unlike cached results from suppliers.
- Parameters:
value- The bean implementation instance. Can benull , in which case no explicit implementation is used.- Returns:
- This object.
- The bean implementation will still have its fields and methods injected via
-
postCreateHook
Registers a post-creation hook to run after the bean is created.Post-creation hooks are executed after the bean is instantiated and after dependency injection has been performed via
ClassInfo.inject(Object, BeanStore).Multiple hooks can be registered and they will be executed in the order they were added.
Notes:
- Hooks are executed every time
run()is called. Sincerun()uses a cachedMemoizer, hooks are only executed once unlessreset()is called. - Hooks are executed after dependency injection, so all
@Injectfields and methods will have been populated before the hook runs. - Hooks can be used for custom initialization logic, logging, wrapping beans with proxies, or any other post-creation processing.
- If a hook throws an exception, bean creation will fail and the exception will propagate to the caller.
- The hook receives the fully initialized bean instance as its parameter.
Example:
// Register multiple post-creation hooks MyServiceservice = BeanInstantiator .of (MyService.class ,myBeanStore ) .postCreateHook(s ->s .initialize()) .postCreateHook(s ->s .loadConfiguration()) .postCreateHook(s ->logger .info("Created service: " +s )) .run();- Parameters:
hook- The post-creation hook to run after bean creation. Cannot benull .- Returns:
- This object.
- Hooks are executed every time
-
silent
Suppresses warning-level log output from this builder.Useful when
asOptional()is preferred and you don't want the underlying log noise that accompanies fallback or factory-abstention paths.Errors and exceptions are still thrown normally; only descriptive log entries are suppressed.
- Returns:
- This object.
-
description
Sets a human-readable description used in log entries and error messages.Useful when the bean type alone doesn't provide enough context (e.g. multiple instances of the same type).
- Parameters:
value- The description. Cannot benull .- Returns:
- This object.
-
wrap
Registers a transformation to apply to the created bean before it is returned.Multiple wrappers may be registered; they are applied in registration order. Each wrapper receives the output of the previous wrapper.
Example:
BeanInstantiator.
of (MyService.class , store) .wrap(LoggingProxy::wrap) .wrap(MetricsProxy::wrap) .run();- Parameters:
wrapper- The wrapper. Cannot benull .- Returns:
- This object.
-
validate
Registers a post-creation validator.The predicate is invoked on the created bean. If it returns
false , anExecutableExceptionis thrown with the supplied message.- Parameters:
predicate- The predicate. Cannot benull .message- The error message used when the predicate returnsfalse . Cannot benull .- Returns:
- This object.
-
or
Registers an alternativeBeanInstantiator.Builderto consult if this builder fails to create the bean.Multiple alternatives may be registered. They are tried in registration order. The first one that succeeds returns its bean; if all fail, the last exception is propagated.
- Parameters:
alternative- The alternative builder. Cannot benull .- Returns:
- This object.
-
builderInitializer
Registers a callback that is invoked on the builder instance beforebuild()is called.Multiple initializers may be registered; they are applied in registration order. The callback receives the builder instance after it has been retrieved (from the bean store, static factory, or constructor) but before any auto-wiring or
inject-basedprocessing.The callback is typed as
Consumer<Object>because the builder type is generally not statically known at the call site (an unchecked cast will typically be required inside the lambda).- Parameters:
initializer- The initializer. Cannot benull .- Returns:
- This object.
-
injectBuilder
Enables@Inject/@Autowiredfield and method injection on the builder instance.When set, after the builder is retrieved (from the bean store, static factory, or constructor), its fields and methods annotated with
@Injector@Autowiredare auto-resolved from the bean store. This is similar to the post-construction injection performed on the resulting bean, but applied to the builder.Default is
false (opt-in).- Returns:
- This object.
-
autoWireBuilder
Enables auto-wiring of bean store entries into matching setter methods on the builder.When set, after the builder is retrieved, every public single-argument setter method is inspected. If the bean store has a bean of a type assignable to the setter's parameter type, the setter is invoked with that bean.
If a parameter is of type
Supplier<X>and the bean store has a bean of typeX, the bean is wrapped in a supplier and passed to the setter (whenunwrapSuppliersdefaulting to true).Default is
false (opt-in).- Returns:
- This object.
-
noBuilder
Disables builder-based bean creation entirely.When set, builder detection is skipped and the bean is instantiated directly via static factory methods or constructors. This is useful when a Builder class is co-located with the bean type (e.g.
Foo.Builder) but the caller wants to use a builder-taking constructor instead.Example:
BeanInstantiator.
of (BasicSwaggerProvider.class , beanStore) .add(SwaggerProvider.Builder.class ,this ) .noBuilder() .run();- Returns:
- This object.
-
scope
Sets the lifecycle scope of the bean being created.BeanInstantiator.Scope.SINGLETONis equivalent to callingcached();BeanInstantiator.Scope.PROTOTYPEresets the cached flag.- Parameters:
value- The scope. Cannot benull .- Returns:
- This object.
-
copy
Returns a copy of this builder with the same configuration.The returned builder shares no mutable state with this one and may be configured independently.
- Returns:
- A new builder pre-populated with this builder's configuration.
-
reset
Resets the builder, builderType, and beanImpl suppliers.This causes them to be re-evaluated on the next call to
run().Notes:
- If an explicit builder instance was set via
builder(Object), it is preserved and not cleared by this method. - If an explicit implementation was set via
impl(Object), it is preserved and not cleared by this method. - Only the cached results from suppliers are reset, not the configuration itself.
- Returns:
- This object.
- If an explicit builder instance was set via
-