Class GuiceBundle.Builder
- java.lang.Object
-
- ru.vyarus.dropwizard.guice.GuiceBundle.Builder
-
- Enclosing class:
- GuiceBundle
public static class GuiceBundle.Builder extends java.lang.ObjectBuilder encapsulates bundle configuration options.
-
-
Constructor Summary
Constructors Constructor Description Builder()
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description GuiceBundle.BuilderautoConfigFilter(java.util.function.Predicate<java.lang.Class<?>> filter)Filter classes which could be recognized as an extension.GuiceBundlebuild()GuiceBundlebuild(com.google.inject.Stage stage)GuiceBundle.BuilderbundleLookup(GuiceyBundleLookup bundleLookup)Configure customGuiceyBundleLookup.GuiceBundle.Builderbundles(GuiceyBundle... bundles)Guicey bundles are mainly useful for extensions (to group installers and extensions installation without auto scan).GuiceBundle.Builderdisable(java.util.function.Predicate<? extends ItemInfo>... predicates)Disable items using disable predicate: all matched items will be disabled.GuiceBundle.BuilderdisableBundleLookup()Disables default bundle lookup.GuiceBundle.BuilderdisableBundles(java.lang.Class<? extends GuiceyBundle>... bundles)Bundles disable is mostly useful for testing.GuiceBundle.BuilderdisableDropwizardBundles(java.lang.Class<? extends io.dropwizard.core.ConfiguredBundle>... bundles)Dropwizard bundles disable is mostly useful for testing.GuiceBundle.BuilderdisableExtensions(java.lang.Class<?>... extensions)Extensions disable mostly useful for testing.GuiceBundle.BuilderdisableInstallers(java.lang.Class<? extends FeatureInstaller>... installers)Disabling installer will lead to avoiding all relative installed extensions.GuiceBundle.BuilderdisableModules(java.lang.Class<? extends com.google.inject.Module>... modules)Modules disable is mostly useful for testing.GuiceBundle.BuilderdropwizardBundles(io.dropwizard.core.ConfiguredBundle... bundles)Dropwizard bundles registration.GuiceBundle.BuilderduplicateConfigDetector(DuplicateConfigDetector detector)Duplicate configuration detector decides what configuration items, registered as instance (guicey bundle, guice module) to consider duplicate (and so avoid duplicates installation).GuiceBundle.BuilderenableAutoConfig(java.lang.String... basePackages)Enables auto scan feature: search for installers and extensions in provided packages.GuiceBundle.Builderextensions(java.lang.Class<?>... extensionClasses)Beans could be registered automatically when auto scan enabled, but if you don't want to use it, you can register beans manually.GuiceBundle.BuilderextensionsOptional(java.lang.Class<?>... extensionClasses)The same asextensions(Class[]), but, in case if no installer recognize extension, will be automatically disabled instead of throwing error.GuiceBundle.BuilderhookAlias(java.lang.String name, java.lang.Class<? extends GuiceyConfigurationHook> hook)Guicey hooks (GuiceyConfigurationHook) may be loaded with system property "guicey.hooks".GuiceBundle.BuilderinjectorFactory(InjectorFactory injectorFactory)Configures customInjectorFactory.GuiceBundle.Builderinstallers(java.lang.Class<? extends FeatureInstaller>... installers)Feature installers registered automatically when auto scan enabled, but if you don't want to use it, you can register installers manually (note: without auto scan default installers will not be registered).GuiceBundle.Builderlisten(GuiceyLifecycleListener... listeners)Guicey broadcast a lot of events in order to indicate lifecycle phases (GuiceyLifecycle).GuiceBundle.BuilderlistenJersey(org.glassfish.jersey.server.monitoring.ApplicationEventListener listener)Shortcut for jetty events and requests listenerenvironment().jersey().register(listener)registration.GuiceBundle.BuilderlistenJetty(org.eclipse.jetty.util.component.LifeCycle.Listener listener)Shortcut for jetty lifecycle listenerenvironment().lifecycle().addEventListener(listener)registration.GuiceBundle.BuilderlistenServer(io.dropwizard.lifecycle.ServerLifecycleListener listener)Shortcut forenvironment().lifecycle().addServerLifecycleListenerregistration.GuiceBundle.Buildermodules(com.google.inject.Module... modules)Multiple module instances of the same type could be registered.GuiceBundle.BuildermodulesOverride(com.google.inject.Module... modules)Register overriding modules, used to override bindings of normal modules.GuiceBundle.BuildernoDefaultInstallers()Disables automaticCoreInstallersBundleandWebInstallersBundleregistration (no installers will be registered by default).GuiceBundle.BuildernoGuiceFilter()DisablesGuiceFilterregistration for both application and admin contexts.GuiceBundle.BuilderonApplicationShutdown(ApplicationShutdownListener listener)Code to execute after complete application shutdown.GuiceBundle.BuilderonApplicationStartup(ApplicationStartupListener listener)Code to execute after complete application startup.<C extends io.dropwizard.core.Configuration>
GuiceBundle.BuilderonGuiceyStartup(GuiceyStartupListener<C> listener)Code to execute after guice injector creation (but still under run phase).<K extends java.lang.Enum<? extends Option> & Option>
GuiceBundle.Builderoption(K option, java.lang.Object value)Options is a generic mechanism to provide internal configuration values for guicey and 3rd party bundles.<K extends java.lang.Enum & Option>
GuiceBundle.Builderoptions(java.util.Map<java.lang.Enum,java.lang.Object> options)Sets multiple options at once.GuiceBundle.BuilderprintAllGuiceBindings()Prints all bindings in guice injector.GuiceBundle.BuilderprintAvailableInstallers()Prints all registered (not disabled) installers with registration source.GuiceBundle.BuilderprintConfigurationBindings()Prints available configuration bindings.GuiceBundle.BuilderprintCustomConfigurationBindings()The same asprintConfigurationBindings(), but hides all dropwizard related paths.GuiceBundle.BuilderprintDiagnosticInfo()Print additional diagnostic logs with startup statistics, installed bundles, installers and resolved extensions and configuration tree.GuiceBundle.BuilderprintExtensionsHelp()Prints extensions usage help: all extension signs recognized by installers.GuiceBundle.BuilderprintGuiceAopMap()Prints all configured guice AOP interceptors and how they apply to methods.GuiceBundle.BuilderprintGuiceAopMap(GuiceAopConfig config)Supposed to be used to understand how guice AOP works (the most often reasons: check aop applied to method and check interceptors order).GuiceBundle.BuilderprintGuiceBindings()Prints guice bindings configured in user-provided modules (excluding guicey and guice own bindings).GuiceBundle.BuilderprintGuiceProvisionTime()Prints guice beans construction time (during application startup) and number of created beans.GuiceBundle.BuilderprintJerseyConfig()Prints all registered jersey extensions (including core dropwizard extensions and everything registered by other dropwizard bundles or manually).GuiceBundle.BuilderprintLifecyclePhases()Split logs with major lifecycle stage names.GuiceBundle.BuilderprintLifecyclePhasesDetailed()Same asprintLifecyclePhases(), but also prints resolved and disabled configuration items.GuiceBundle.BuilderprintSharedStateUsage()PrintsSharedConfigurationStateusage history after application startup.GuiceBundle.BuilderprintStartupTime()Prints detailed application startup (and shutdown) times.GuiceBundle.BuilderprintWebMappings()Prints all configured filters and servlets (including guiceServletModuledeclarations.GuiceBundle.BuildersearchCommands()NOTE: will not scan if auto scan not enabled (packages not configured withenableAutoConfig(String...)).GuiceBundle.BuilderstrictScopeControl()Enables strict control of beans instantiation context: all beans must be instantiated by guice, except beans annotated withJerseyManaged.GuiceBundle.BuilderuniqueItems(java.lang.Class<?>... configurationItems)Grant uniqueness for specified instance items: guicey bundles, guice modules and dropwizard bundles, registered through guicey api (dropwizardBundles(ConfiguredBundle[])andGuiceyOptions.TrackDropwizardBundles).GuiceBundle.BuilderuseHK2ForJerseyExtensions()Manage jersey extensions (resources, jersey filters etc.) with HK2 by default instead of guice (the same effect as ifJerseyManagedannotation would be set on all beans).GuiceBundle.BuilderwhenConfigurationReady(java.util.function.Consumer<GuiceyEnvironment> runPhaseAction)Delayed configuration block.GuiceBundle.BuilderwithSharedState(java.util.function.Consumer<SharedConfigurationState> stateAction)Guicey manage application-wide shared state object to simplify cases when such state is required during configuration.
-
-
-
Method Detail
-
option
public <K extends java.lang.Enum<? extends Option> & Option> GuiceBundle.Builder option(K option, java.lang.Object value)
Options is a generic mechanism to provide internal configuration values for guicey and 3rd party bundles. SeeGuiceyOptionsas options example. Bundles may define their own enums in the same way to use options mechanism.Options intended to be used for development time specific configurations (most likely low level options to slightly change behaviour). Also, in contrast to internal booleans (e.g. in main bundle), options are accessible everywhere and may be used by other 3rd party module or simply for reporting.
Options may be set only on application level. Guicey bundles could access option values through bootstrap object. Guice service could access options through options bean. Installers could use
WithOptionsto get access to options. Options metadata for reporting is available through guice bean.Options may be used instead of shortcut methods when configuration value is dynamic (without options it would not be impossible to configure without breaking builder flow and additional if statements).
Note: each option declares exact option type and provided value is checked for type compatibility.
- Type Parameters:
K- helper type for option signature definition- Parameters:
option- option enumvalue- option value (not null)- Returns:
- builder instance for chained calls
- Throws:
java.lang.NullPointerException- is null value providedjava.lang.IllegalArgumentException- if provided value incompatible with option type- See Also:
for more details,GuiceyOptions,InstallersOptions
-
options
public <K extends java.lang.Enum & Option> GuiceBundle.Builder options(java.util.Map<java.lang.Enum,java.lang.Object> options)
Sets multiple options at once. Method would be useful for options lookup implementations.Note:
Optiontype is not mixed with enum in declaration to simplify usage, but used enums must be correct options.Use provided
OptionsMapperutility to map options from system properties or environment variables. It supports basic string conversions. For example:
Will set injector stage option from STAGE environment variable. If variable is not set - default value used. If STAGE set to, for example "DEVELOPMENT" (must be Stage enum value) then Stage.DEVELOPMENT will be set as option value..options(new OptionsMapper() .env("STAGE", GuiceyOptions.InjectorStage) .map())Also, mapper could map generic options definitions from system properties (prefixed):
See.options(new OptionsMapper() .props("option.") .map())OptionsMapperfor more usage details.- Type Parameters:
K- helper type for option signature definition- Parameters:
options- options map (not null)- Returns:
- builder instance for chained calls
- Throws:
java.lang.NullPointerException- is null value provided for any optionjava.lang.IllegalArgumentException- if any provided value incompatible with option type- See Also:
for more info,OptionsMapper
-
injectorFactory
public GuiceBundle.Builder injectorFactory(InjectorFactory injectorFactory)
Configures customInjectorFactory. Required by some guice extensions like governator.- Parameters:
injectorFactory- custom guice injector factory- Returns:
- builder instance for chained calls
-
bundleLookup
public GuiceBundle.Builder bundleLookup(GuiceyBundleLookup bundleLookup)
Configure customGuiceyBundleLookup. Lookup provides an easy way to indirectly installGuiceyBundlebundles. Default implementation support lookup by system property.- Parameters:
bundleLookup- custom bundle lookup implementation- Returns:
- builder instance for chained calls
- See Also:
DefaultBundleLookup,duplicateConfigDetector(DuplicateConfigDetector)
-
disableBundleLookup
public GuiceBundle.Builder disableBundleLookup()
Disables default bundle lookup.- Returns:
- builder instance for chained calls
-
enableAutoConfig
public GuiceBundle.Builder enableAutoConfig(java.lang.String... basePackages)
Enables auto scan feature: search for installers and extensions in provided packages.When no packages specified, scan would be performed for application class package.
- Parameters:
basePackages- packages to scan extensions in- Returns:
- builder instance for chained calls
- See Also:
GuiceyOptions.ScanPackages
-
autoConfigFilter
public GuiceBundle.Builder autoConfigFilter(java.util.function.Predicate<java.lang.Class<?>> filter)
Filter classes which could be recognized as an extension. Filter applied before extension recognition, so you could slightly increase startup time by avoiding extension detection for some classes. Filter also applied for guice bindings (extensions recognized from guice bindings).For example, if you want to exclude all annotated classes:
autoConfigFilter(type -> !type.isAnnotationPresent(Stub.class))For simplicity, use
ClassFiltersutility with static import for building predicates:autoConfigFilter(ignoreAnnotated(Stub.class))Another example, suppose you want spring-style configuration: accept only classes with some annotation:
autoConfigFilter(annotated(Component.class))The difference with
disable(java.util.function.Predicate[])predicate: by default, guicey would apply all installers for each class to detect extension and disable predicate prevents recognized extension installation, whereas this filter prevents classes from being detected. As a result, even if filtered class was an actual extension - it would not be recognized and not registered (not visible in reports).Multiple filters could be specified. Filter applied only for extensions (does not affect commands and installers search).
Be aware that filter would be also called for all guice bindings (if extension from binding recognition enabled). So filter could be used to filter recognitions from bindings too.
- Parameters:
filter- filter predicate for classes suitable for extensions detection- Returns:
- builder instance for chained calls
- See Also:
for simple annotation predicates implementation
-
duplicateConfigDetector
public GuiceBundle.Builder duplicateConfigDetector(DuplicateConfigDetector detector)
Duplicate configuration detector decides what configuration items, registered as instance (guicey bundle, guice module) to consider duplicate (and so avoid duplicates installation). By default, multiple instances of the same type allowed (the same as with dropwizard bundles - you can register multiple instances). But same instances or equal (Object.equals(Object)) instances are considered duplicate. If you need to accept only one instance of bundle or module, simply implement equals method to make all instances equal. Custom deduplicatation implementation may be required for 3rd party instances, where proper equals implementation is impossible (or for more complicated duplicates detection logic).Example situation: suppose one common bundle (or guice module) is used by two other bundles, so it would be registered in two bundles, but, if these bundles would be used together, then two instances of common bundle would be registered, which is often not desired. To workaround such case, bundle must implement proper equals method or custom duplication detector implementation must be used.
Use
LegacyModeDuplicatesDetectorto simulate legacy guicey behaviour when only one instance of type is allowed (if old behaviour is important). UseuniqueItems(Class[])to grant uniqueness for some items only.- Parameters:
detector- detector implementation- Returns:
- builder instance for chained calls
-
uniqueItems
public GuiceBundle.Builder uniqueItems(java.lang.Class<?>... configurationItems)
Grant uniqueness for specified instance items: guicey bundles, guice modules and dropwizard bundles, registered through guicey api (dropwizardBundles(ConfiguredBundle[])andGuiceyOptions.TrackDropwizardBundles). That means that if multiple instances of specified type would be registered, only one instance will actually be used (and other would be considered as duplicate configurations).Method actually registers custom detector implementation
duplicateConfigDetector(DuplicateConfigDetector)and so can't be used together with other custom duplicates detector.Warning: in contrast to other builder methods, configurations from multiple method calls are not aggregated (each new call to overrides previous configuration), so specify all unique items in one call.
- Parameters:
configurationItems- instance configuration items (bundles or modules) to grant uniqueness- Returns:
- builder instance for chained calls
-
modules
public GuiceBundle.Builder modules(com.google.inject.Module... modules)
Multiple module instances of the same type could be registered. If module uniqueness is important useUniqueModulewith correct equals implementation or implement custom deduplication logic induplicateConfigDetector(DuplicateConfigDetector).These modules are registered under initialization phase where you don't have access for configuration or environment objects. To workaround this you can use *AwareModule interfaces, or extend from
DropwizardAwareModuleand required objects will be set just before configuration start.Alternatively, registration could be delayed with
whenConfigurationReady(java.util.function.Consumer).And another option is to register module insideGuiceyBundle.run(GuiceyEnvironment), which is called under run phase.- Parameters:
modules- one or more guice modules- Returns:
- builder instance for chained calls
- See Also:
BootstrapAwareModule,ConfigurationAwareModule,EnvironmentAwareModule,OptionsAwareModule,DropwizardAwareModule
-
modulesOverride
public GuiceBundle.Builder modulesOverride(com.google.inject.Module... modules)
Register overriding modules, used to override bindings of normal modules. Internally guiceModules.override(Module...)is used. If binding is present in normal module and overriding module then overriding module binding is used. Bindings in overriding modules, not present in normal modules are simply added to context (as usual module).The main purpose for overriding modules is testing, but it also could be used (in rare cases) to amend existing guice context (for example, in case when you do not control all bindings, but need to hot fix something).
Overriding modules behave the same as normal modules: they are inspected for *AwareModule interfaces to inject dropwizard objects. Overriding module could be disabled with
disableModules(Class[])or genericdisable(Predicate[]).- Parameters:
modules- overriding modules- Returns:
- builder instance for chained calls
- See Also:
modules(Module...),to override overridden bindings in test (edge case(
-
searchCommands
public GuiceBundle.Builder searchCommands()
NOTE: will not scan if auto scan not enabled (packages not configured withenableAutoConfig(String...)).Enables commands classpath search. All found commands are instantiated and registered in bootstrap. Default constructor is used for simple commands, but
EnvironmentCommandmust have constructor withApplicationargument.By default, commands search is disabled.
- Returns:
- builder instance for chained calls
- See Also:
CommandSupport,GuiceyOptions.SearchCommands
-
noDefaultInstallers
public GuiceBundle.Builder noDefaultInstallers()
Disables automaticCoreInstallersBundleandWebInstallersBundleregistration (no installers will be registered by default).- Returns:
- builder instance for chained calls
- See Also:
GuiceyOptions.UseCoreInstallers
-
noGuiceFilter
public GuiceBundle.Builder noGuiceFilter()
DisablesGuiceFilterregistration for both application and admin contexts. Without guice filter registered, guiceServletModuleregistrations are useless (because they can't be used). So guice servlet modules support will be disabled: no request or session scopes may be used and registrations of servlet modules will be denied (binding already declared exception). Even with disabled guice filter, request and response objects provider injections still may be used in resources (will work through HK2 provider).Guice servlets initialization took ~50ms, so injector creation will be a bit faster after disabling.
Soft deprecation: try to avoid hk2 direct usage if possible, someday HK2 support will be removed. In case of hk2 remove, guice request scope will be mandatory.
- Returns:
- builder instance for chained calls
- See Also:
GuiceyOptions.GuiceFilterRegistration
-
installers
@SafeVarargs public final GuiceBundle.Builder installers(java.lang.Class<? extends FeatureInstaller>... installers)
Feature installers registered automatically when auto scan enabled, but if you don't want to use it, you can register installers manually (note: without auto scan default installers will not be registered).Also, could be used to add installers from packages not included in auto scanning.
- Parameters:
installers- feature installer classes to register- Returns:
- builder instance for chained calls
-
extensions
public GuiceBundle.Builder extensions(java.lang.Class<?>... extensionClasses)
Beans could be registered automatically when auto scan enabled, but if you don't want to use it, you can register beans manually.Guice injector will instantiate beans and registered installers will be used to recognize and properly register provided extension beans. Startup will fail if bean not recognized by installers.
Also, could be used to add beans from packages not included in auto scanning.
Alternatively, you can manually bind extensions in guice module and they would be recognized (
GuiceyOptions.AnalyzeGuiceModules).If extension registration depends on configuration value then use
whenConfigurationReady(java.util.function.Consumer)or register extension insideGuiceyBundle.run(GuiceyEnvironment), which is called under run phase.- Parameters:
extensionClasses- extension bean classes to register- Returns:
- builder instance for chained calls
-
extensionsOptional
public GuiceBundle.Builder extensionsOptional(java.lang.Class<?>... extensionClasses)
The same asextensions(Class[]), but, in case if no installer recognize extension, will be automatically disabled instead of throwing error. Useful for optional extensions declaration, which must be activated only when some 3rd party bundle appear. For example, it could be some diagnostic info provider, which must be activated when 3rd party diagnostic bundle is enabled (via bundles lookup or with hook).Alternatively, you can manually bind extensions in guice module and they would be recognized (
GuiceyOptions.AnalyzeGuiceModules). Extensions with no available target installer will simply wouldn't be detected (because installers used for recognition) and so there is no need to mark them as optional in this case.- Parameters:
extensionClasses- extension bean classes to register- Returns:
- builder instance for chained calls
-
bundles
public GuiceBundle.Builder bundles(GuiceyBundle... bundles)
Guicey bundles are mainly useful for extensions (to group installers and extensions installation without auto scan). Bundles lifecycle is the same as dropwizard bundles and so it could be used together.Multiple bundle instances of the same type could be registered. If bundle uniqueness is important use
UniqueGuiceyBundlewith correct equals implementation or implement custom deduplication logic induplicateConfigDetector(DuplicateConfigDetector).- Parameters:
bundles- guicey bundles- Returns:
- builder instance for chained calls
-
dropwizardBundles
public GuiceBundle.Builder dropwizardBundles(io.dropwizard.core.ConfiguredBundle... bundles)
Dropwizard bundles registration. There is no difference with direct bundles registration (withBootstrap.addBundle(ConfiguredBundle), which is actually called almost immediately), except guicey tracking (registered bundles are showed in diagnostic report), ability to disable bundle and automatic duplicates detection (seeduplicateConfigDetector(DuplicateConfigDetector)).Only bundles registered with guicey api are checked! For example, if you register one instance of the same bundle directly into bootstrap and another one with guicey api - guicey will not be able to track duplicate registration. So it's better to register all bundles through guicey api.
By default, guicey will also track transitive bundles registrations (when registered bundle register other bundles) so disable and deduplication logic will apply to them too. Tracking could be disabled with
GuiceyOptions.TrackDropwizardBundlesoption.- Parameters:
bundles- guicey bundles- Returns:
- builder instance for chained calls
-
disableInstallers
@SafeVarargs public final GuiceBundle.Builder disableInstallers(java.lang.Class<? extends FeatureInstaller>... installers)
Disabling installer will lead to avoiding all relative installed extensions. If you have manually registered extensions for disabled installer then remove their registration. Classpath scan extensions will be ignored (not installed, because no installer to recognize them).Disabling installer may be used to replace some existing installer with modified version (probably fixed): disable existing installer and register new custom installer.
- Parameters:
installers- feature installer types to disable- Returns:
- builder instance for chained calls
-
disableExtensions
public final GuiceBundle.Builder disableExtensions(java.lang.Class<?>... extensions)
Extensions disable mostly useful for testing. In some cases, it could be used to disable some extra extensions installed with classpath scan or bundle.Disabling could be used for removing some temporal extensions like rest api stubs.
For extensions, detected from guice bindings, disabling extension would remove existing guice binding (when module analysis enabled).
- Parameters:
extensions- extensions to disable (manually added, registered by bundles or with classpath scan)- Returns:
- builder instance for chained calls
-
disableModules
@SafeVarargs public final GuiceBundle.Builder disableModules(java.lang.Class<? extends com.google.inject.Module>... modules)
Modules disable is mostly useful for testing. In some cases, it could be used to disable some extra modules installed by some bundle. But, generally, try to avoid manual modules disabling for clearer application configuration.Option could also disable inner modules (registered by modules transitively), but only if bindings analysis is not disabled (by
GuiceyOptions.AnalyzeGuiceModules). Inner modules can't be removed from overriding modules, because only normal modules are analyzed.When bindings analysis is disabled this option can disable only directly registered modules (with
modules(Module...)or in bundleGuiceyBootstrap.modules(Module...).- Parameters:
modules- guice module types to disable- Returns:
- builder instance for chained calls
-
disableBundles
@SafeVarargs public final GuiceBundle.Builder disableBundles(java.lang.Class<? extends GuiceyBundle>... bundles)
Bundles disable is mostly useful for testing. In some cases, it could be used to disable some transitive bundle (bundle installed by some registered bundle withGuiceyBootstrap.bundles(GuiceyBundle...)).- Parameters:
bundles- guicey bundles to disable- Returns:
- builder instance for chained calls
-
disableDropwizardBundles
@SafeVarargs public final GuiceBundle.Builder disableDropwizardBundles(java.lang.Class<? extends io.dropwizard.core.ConfiguredBundle>... bundles)
Dropwizard bundles disable is mostly useful for testing. Note that it can disable only bundles directly registered through guicey api or bundles registered by them (if dropwizard bundles tracking not disabled withGuiceyOptions.TrackDropwizardBundles).- Parameters:
bundles- guicey bundles to disable- Returns:
- builder instance for chained calls
-
disable
@SafeVarargs public final GuiceBundle.Builder disable(java.util.function.Predicate<? extends ItemInfo>... predicates)
Disable items using disable predicate: all matched items will be disabled. Predicate is called just after first item registration and, if it will evaluate to true, then item marked as disabled. Predicate receive only disableable items: guicey bundle, installer, extension or guice module (directly registered).Also, predicate is called on registration for all already registered items to make predicate registration moment not important.
Essentially, predicates are the same as calling direct disable methods: items, disabled by predicate, will be marked as disabled by predicate registration context (application or guicey bundle).
Mostly useful for testing, but in some cases could be used directly (e.g. could be used for sisabling temporary extensions, like rest api stubs).
Use
Predicate.and(Predicate),Predicate.or(Predicate)andPredicate.negate()to combine complex predicates from simple ones fromDisableshelper.Item passed only one time after initial registration and so item object will have only basic fields: item type, item class and item registration scope (who register it).
For example, disable all installers, registered from application root except SomeInstallerType:
import static ru.vyarus.dropwizard.guice.module.context.Disables.* builder.disable(installer() .and(registeredBy(Application.class)) .and(type(SomeInstallerType.class).negate());Items could be disabled just by class, no matter what type they are:
import static ru.vyarus.dropwizard.guice.module.context.Disables.* builder.disable(type(MyExtension.class, MyInstaller.class, MyBundle.class, MyModule.class));For instance types (bundles, modules), when multiple instances of the same class may appear, exact instance could be disabled (predicate would be called for each new instance separately, avoiding equal duplicates).
- Parameters:
predicates- disable predicates- Returns:
- builder instance for chained calls
- See Also:
for common predicates
-
listen
public GuiceBundle.Builder listen(GuiceyLifecycleListener... listeners)
Guicey broadcast a lot of events in order to indicate lifecycle phases (GuiceyLifecycle). This could be useful for diagnostic logging (likeprintLifecyclePhases()) or to implement special behaviours on installers, bundles, modules extensions (listeners have access to everything). For example,ConfigurationAwareModulelike support for guice modules could be implemented with listeners.Configuration items (modules, extensions, bundles) are not aware of each other and listeners could be used to tie them. For example, to tell bundle if some other bundles registered (limited applicability, but just for example).
You can also use
GuiceyLifecycleAdapterwhen you need to handle multiple events (it replaces direct events handling with simple methods).Listener is not registered if equal listener were already registered (
Setused as listeners storage), so if you need to be sure that only one instance of some listener will be used implementObject.equals(Object)andObject.hashCode().- Parameters:
listeners- guicey lifecycle listeners- Returns:
- builder instance for chained calls
- See Also:
GuiceyLifecycle,GuiceyLifecycleAdapter,UniqueGuiceyLifecycleListener
-
strictScopeControl
public GuiceBundle.Builder strictScopeControl()
Enables strict control of beans instantiation context: all beans must be instantiated by guice, except beans annotated withJerseyManaged. When bean instantiated in wrong context exception would be thrown.It is useful if you write your own installers or to simply ensure correctness in doubtful cases.
Do not use for production! It is intended to be used mostly in tests or to diagnose problems during development.
To implicitly enable this check in all tests use
PropertyBundleLookup.enableBundles(HK2DebugBundle.class).Soft deprecation: try to avoid hk2 direct usage if possible, someday HK2 support will be removed
- Returns:
- builder instance for chained calls
- See Also:
HK2DebugBundle
-
useHK2ForJerseyExtensions
public GuiceBundle.Builder useHK2ForJerseyExtensions()
Manage jersey extensions (resources, jersey filters etc.) with HK2 by default instead of guice (the same effect as ifJerseyManagedannotation would be set on all beans). Use this option if you want to use jersey specific resource features (like @Context bindings) and completely delegate management to HK2.IMPORTANT: this will activate HK2 bridge usage (to be able to inject guice beans) and so you will need to provide bridge dependency (org.glassfish.hk2:guice-bridge:2.6.1). Startup will fail if dependency is not available.
WARNING: you will not be able to use guice AOP on beans managed by HK2!
Soft deprecation: try to avoid hk2 direct usage if possible, someday HK2 support will be removed
- Returns:
- builder instance for chained calls
- See Also:
InstallersOptions.JerseyExtensionsManagedByGuice,JerseyManaged,GuiceManaged
-
printDiagnosticInfo
public GuiceBundle.Builder printDiagnosticInfo()
Print additional diagnostic logs with startup statistics, installed bundles, installers and resolved extensions and configuration tree.Statistics shows mainly where guice spent most time. Configuration info is useful for configuration problems resolution. Also, logs useful for better understanding how guicey works.
If custom logging format is required use
ConfigurationDiagnosticdirectly.May be enabled on compiled application with a system property:
-Dguicey.hooks=diagnostic(hook will also enable some other reports).- Returns:
- builder instance for chained calls
- See Also:
ConfigurationDiagnostic,DiagnosticHook
-
printExtensionsHelp
public GuiceBundle.Builder printExtensionsHelp()
Prints extensions usage help: all extension signs recognized by installers. Installers printed in execution order.Not that custom installers must provide this information by overriding
FeatureInstaller.getRecognizableSigns().- Returns:
- builder instance for chained calls
-
printAvailableInstallers
public GuiceBundle.Builder printAvailableInstallers()
Prints all registered (not disabled) installers with registration source. Useful to see all supported extension types when multiple guicey bundles registered and available features become not obvious from application class.In contrast to
printDiagnosticInfo()shows all installers (including installers not used by application extensions). Installers report intended only to show available installers and will not show duplicate installers registrations or installers disabling (use diagnostic reporting for all configuration aspects). Also, report will indicate installers marker interfaces and so it will be obvious what installer did: install by type or by object, perform custom guice bindings or perform jersey specific installations.- Returns:
- builder instance for chained calls
- See Also:
ConfigurationDiagnostic
-
printConfigurationBindings
public GuiceBundle.Builder printConfigurationBindings()
Prints available configuration bindings. Use it to see available bindings or debug missed bindings as report shown before actual injector start. UseprintCustomConfigurationBindings()to see only custom paths (without dropwizard configurations).Safe to use with other print* options.
Info: guicey analyze configuration object (prepared by dropwizard) with jackson serialization api and binds all readable configuration values by path (e.g.
@inject @Config("some.path") String prop;. Also, unique sub configuration objects are recognized and may be used directly (@Inject @Config SubConfig subConf). Introspected configuration object is accessible from lifecycle events, gucie modules, guicey bundles and by direct injection.May be enabled on compiled application with a system property:
-Dguicey.hooks=diagnostic(hook will also enable some other reports).- Returns:
- builder instance for chained calls
- See Also:
ConfigurationTree,Config
-
printCustomConfigurationBindings
public GuiceBundle.Builder printCustomConfigurationBindings()
The same asprintConfigurationBindings(), but hides all dropwizard related paths. Use to see bindings of your custom configuration classes.- Returns:
- builder instance for chained calls
-
printGuiceBindings
public GuiceBundle.Builder printGuiceBindings()
Prints guice bindings configured in user-provided modules (excluding guicey and guice own bindings). Identifies bindings overrides from overriding modules, aop and undeclared (JIT) bindings.May be enabled on compiled application with a system property:
-Dguicey.hooks=diagnostic(hook will also enable some other reports).- Returns:
- builder instance for chained calls
- See Also:
to show entire injector state
-
printAllGuiceBindings
public GuiceBundle.Builder printAllGuiceBindings()
Prints all bindings in guice injector.- Returns:
- builder instance for chained calls
- See Also:
to show only user-provided bindings
-
printGuiceAopMap
public GuiceBundle.Builder printGuiceAopMap()
Prints all configured guice AOP interceptors and how they apply to methods. In most cases this general report will be not useful as it will contain too much information. It's better to useprintGuiceAopMap(GuiceAopConfig)and filter all non interesting bindings.- Returns:
- builder instance for chained calls
-
printGuiceAopMap
public GuiceBundle.Builder printGuiceAopMap(GuiceAopConfig config)
Supposed to be used to understand how guice AOP works (the most often reasons: check aop applied to method and check interceptors order). In contrast to other reports, this one is more a specialized tool for development.Multiple reports could be configured (in some cases it is simpler to declare few different but simple configurations rather then one complex).
- Parameters:
config- report configuration- Returns:
- builder instance for chained calls
-
printGuiceProvisionTime
public GuiceBundle.Builder printGuiceProvisionTime()
Prints guice beans construction time (during application startup) and number of created beans. Suitable for:- Verifying providers (and provider methods) performance
- Prototype scope mis-usage (detect too many bean instantiations)
- Jit bindings misuse (usually mistakes)
By default, the report prints only startup time data. If you need to measure time for application runtime, construct diagnostic manually:
This might be used in tests to control guice beans creation amount and time.// false to avoid startup report GuiceProvisionDiagnostic report = new GuiceProvisionDiagnostic(false); // registre report GuiceBundle....bundles(report); // clear collected data before required point report.clear(); ... // generate report after measured actions logger.info("Guice provision time {}", report.renderReport());For compiled application report could be activated with:
-Dguicey.hooks=provision-time- Returns:
- builder instance for chained calls
- See Also:
for simple usage in tests
-
printLifecyclePhases
public GuiceBundle.Builder printLifecyclePhases()
Split logs with major lifecycle stage names. Useful for debugging (to better understand at what stage your code is executed). Also, could be used for light profiling as time since startup is printed for each phase (and for shutdown phases). And, of course, could be used for better guicey understanding.- Returns:
- builder instance for chained calls
- See Also:
LifecycleDiagnostic
-
printLifecyclePhasesDetailed
public GuiceBundle.Builder printLifecyclePhasesDetailed()
Same asprintLifecyclePhases(), but also prints resolved and disabled configuration items.May be enabled on compiled application with a system property:
-Dguicey.hooks=diagnostic(hook will also enable some other reports).- Returns:
- builder instance for chained calls
- See Also:
LifecycleDiagnostic
-
printWebMappings
public GuiceBundle.Builder printWebMappings()
Prints all configured filters and servlets (including guiceServletModuledeclarations.May be enabled on compiled application with a system property:
-Dguicey.hooks=diagnostic(hook will also enable some other reports).- Returns:
- builder instance for chained calls
-
printJerseyConfig
public GuiceBundle.Builder printJerseyConfig()
Prints all registered jersey extensions (including core dropwizard extensions and everything registered by other dropwizard bundles or manually).May be enabled on compiled application with a system property:
-Dguicey.hooks=diagnostic(hook will also enable some other reports).- Returns:
- builder instance for chained calls
-
printStartupTime
public GuiceBundle.Builder printStartupTime()
Prints detailed application startup (and shutdown) times. Useful for startup slowness investigations and initialization order validation (executed hooks and budles order).Time measured from guice bundle creation. Report instruments
BootstrapandLifecycleEnvironmentobjects to measure bunldes and managed objects times.Init time measured as time from guice bundle creation until the last dropwizard bundle init (bundles registered before guice bundle can't be measured; application init method time will go to run phase). Run tim measured as time from init until the last dropwizard bundle run (configuration and environment creation measured separately appears under run phase; application run method time will go to web phase). Web time is a time after run until jersey lifecycle notification (server started).
Overall, report shows almost all application startup time with exact phases. Plus all guicey internal actions.
For compiled application report could be activated with:
-Dguicey.hooks=startup-time- Returns:
- builder instance for chained calls
- See Also:
StartupTimeHook
-
printSharedStateUsage
public GuiceBundle.Builder printSharedStateUsage()
PrintsSharedConfigurationStateusage history after application startup. The report shows:- What objects stored in state
- Who accessed stored objects (preserving access order)
- Misses (requesting not yet available values)
- Never set, but requested objects (including never called state value listeners).
Note that report could be obtained at any time from the shared state object directly:
SharedConfigurationState.getAccessReport()(could be useful for resolving problems before application startup).- Returns:
- builder instance for chained calls
-
hookAlias
public GuiceBundle.Builder hookAlias(java.lang.String name, java.lang.Class<? extends GuiceyConfigurationHook> hook)
Guicey hooks (GuiceyConfigurationHook) may be loaded with system property "guicey.hooks". But it may be not comfortable to always declare full class name (e.g. -Dguicey.hooks=com.foo.bar.Hook,..). Instead short alias name may be used: -Dguicey.hooks=alias1, alias2.By default, diagnostic hook is aliased as "diagnostic" in order to be able to enable diagnostic reporting for compiled application (
-Dguicey.hooks=diagnostic).- Parameters:
name- alias namehook- hook class to alias- Returns:
- builder instance for chained calls
-
whenConfigurationReady
public GuiceBundle.Builder whenConfigurationReady(java.util.function.Consumer<GuiceyEnvironment> runPhaseAction)
Delayed configuration block. Would run under run phase where configuration and environment objects would be available. Essentially, this is the same point as guicey bundles run (GuiceyBundle.run( ru.vyarus.dropwizard.guice.module.installer.bundle.GuiceyEnvironment)), but called just before bundles processing.Useful when guice modules require configuration values or when extensions registration depends on configuration values.
Note: guice injector is not available yet!
Method is not started with "on" or "listen" as other methods to differentiate this configuration method from pure listeners.
- Parameters:
runPhaseAction- action to execute under run phase- Returns:
- builder instance for chained calls
-
withSharedState
public GuiceBundle.Builder withSharedState(java.util.function.Consumer<SharedConfigurationState> stateAction)
Guicey manage application-wide shared state object to simplify cases when such state is required during configuration. It may be used by bundles or hooks to "communicate". For example, server pages bundles use this to unify global configuration. Unified place intended to replace all separate "hacks" and so simplify testing. Shared application state could be accessed statically anywhere during application life.Caution: this is intended to be used only in cases when there is no other option except global state.
This method could be useful for possible hook needs (maybe hooks communications) because there is no other way to access shared state by hooks (bundles may use special api or reference by application instance)
- Parameters:
stateAction- state action- Returns:
- builder instance for chained calls
-
onGuiceyStartup
public <C extends io.dropwizard.core.Configuration> GuiceBundle.Builder onGuiceyStartup(GuiceyStartupListener<C> listener)
Code to execute after guice injector creation (but still under run phase). May be used for manual configurations (registrations into dropwizard environment).Listener will be called on environment command start too.
Note: there is no registration method for this listener in main guice bundle builder (
GuiceBundle.Builder) because it is assumed, that such blocks would always be wrapped with bundles to improve application readability.- Type Parameters:
C- configuration type- Parameters:
listener- listener to call after injector creation- Returns:
- builder instance for chained calls
-
onApplicationStartup
public GuiceBundle.Builder onApplicationStartup(ApplicationStartupListener listener)
Code to execute after complete application startup. For server command it would happen after jetty startup and for lightweight guicey test helpers (TestGuiceyApp) - after guicey start (as jetty not started in this case). In both cases, application completely started at this moment. Suitable for reporting.If you need to listen only for real server startup then use
listenServer(io.dropwizard.lifecycle.ServerLifecycleListener)instead.Not called on custom command execution (because no lifecycle involved in this case). In this case you can use
onGuiceyStartup(GuiceyStartupListener)as always executed point.- Parameters:
listener- listener to call on server startup- Returns:
- builder instance for chained calls
-
onApplicationShutdown
public GuiceBundle.Builder onApplicationShutdown(ApplicationShutdownListener listener)
Code to execute after complete application shutdown. Called not only for real application but for environment commands and lightweight guicey test helpers (TestGuiceyApp). Suitable for closing additional resources.If you need to listen only for real server shutdown then use
listenServer(io.dropwizard.lifecycle.ServerLifecycleListener)instead.Not called on command execution because no lifecycle involved in this case.
- Parameters:
listener- listener to call on server startup- Returns:
- builder instance for chained calls
-
listenServer
public GuiceBundle.Builder listenServer(io.dropwizard.lifecycle.ServerLifecycleListener listener)
Shortcut forenvironment().lifecycle().addServerLifecycleListenerregistration.Note that server listener is called only when jetty starts up and so will not be called with lightweight guicey test helpers
TestGuiceyApp. Prefer usingonApplicationStartup(ApplicationStartupListener)to be correctly called in tests (of course, if not server-only execution is desired).Not called for custom command execution.
- Parameters:
listener- server startup listener.- Returns:
- builder instance for chained calls
-
listenJetty
public GuiceBundle.Builder listenJetty(org.eclipse.jetty.util.component.LifeCycle.Listener listener)
Shortcut for jetty lifecycle listenerenvironment().lifecycle().addEventListener(listener)registration.Lifecycle listeners are called with lightweight guicey test helpers
TestGuiceyAppwhich makes them perfectly suitable for reporting.If only startup event is required, prefer
onApplicationStartup(ApplicationStartupListener)method as more expressive and easier to use.Listeners are not called on custom command execution.
- Parameters:
listener- jetty- Returns:
- builder instance for chained calls
-
listenJersey
public GuiceBundle.Builder listenJersey(org.glassfish.jersey.server.monitoring.ApplicationEventListener listener)
Shortcut for jetty events and requests listenerenvironment().jersey().register(listener)registration.Listeners are not called on custom command execution.
- Parameters:
listener- listener instance- Returns:
- builder instance for chained calls
-
build
public GuiceBundle build(com.google.inject.Stage stage)
- Parameters:
stage- stage to run injector with- Returns:
- bundle instance
- See Also:
GuiceyOptions.InjectorStage
-
build
public GuiceBundle build()
- Returns:
- bundle instance with implicit PRODUCTION stage
- See Also:
GuiceyOptions.InjectorStage
-
-