Class GuiceBundle.Builder

  • Enclosing class:
    GuiceBundle

    public static class GuiceBundle.Builder
    extends java.lang.Object
    Builder encapsulates bundle configuration options.
    • Constructor Detail

      • Builder

        public Builder()
    • Method Detail

      • 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 (like printLifecyclePhases()) or to implement special behaviours on installers, bundles, modules extensions (listeners have access to everything). For example, ConfigurationAwareModule like 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 GuiceyLifecycleAdapter when you need to handle multiple events (it replaces direct events handling with simple methods).

        Listener is not registered if equal listener were already registered (Set used as listeners storage), so if you need to be sure that only one instance of some listener will be used implement Object.equals(Object) and Object.hashCode().

        Parameters:
        listeners - guicey lifecycle listeners
        Returns:
        builder instance for chained calls
        See Also:
        GuiceyLifecycle, GuiceyLifecycleAdapter, UniqueGuiceyLifecycleListener
      • option

        public <K extends java.lang.Enum & OptionGuiceBundle.Builder option​(K option,
                                                                              java.lang.Object value)
        Options is a generic mechanism to provide internal configuration values for guicey and 3rd party bundles. See GuiceyOptions as 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 WithOptions to 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 enum
        value - option value (not null)
        Returns:
        builder instance for chained calls
        Throws:
        java.lang.NullPointerException - is null value provided
        java.lang.IllegalArgumentException - if provided value incompatible with option type
        See Also:
        for more details, GuiceyOptions, InstallersOptions
      • options

        public <K extends java.lang.Enum & OptionGuiceBundle.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: Option type is not mixed with enum in declaration to simplify usage, but used enums must be correct options.

        Use provided OptionsMapper utility to map options from system properties or environment variables. It supports basic string conversions. For example:

        
             .options(new OptionsMapper()
                         .env("STAGE", GuiceyOptions.InjectorStage)
                         .map())
         
        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.

        Also, mapper could map generic options definitions from system properties (prefixed):

        
         .options(new OptionsMapper()
                         .props("option.")
                         .map())
         
        See OptionsMapper for 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 option
        java.lang.IllegalArgumentException - if any provided value incompatible with option type
        See Also:
        for more info, OptionsMapper
      • injectorFactory

        public GuiceBundle.Builder injectorFactory​(InjectorFactory injectorFactory)
        Configures custom InjectorFactory. Required by some guice extensions like governator.
        Parameters:
        injectorFactory - custom guice injector factory
        Returns:
        builder instance for chained calls
      • 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. When enabled, all core installers are registered automatically.
        Parameters:
        basePackages - packages to scan extensions in
        Returns:
        builder instance for chained calls
        See Also:
        GuiceyOptions.ScanPackages
      • 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 LegacyModeDuplicatesDetector to simulate legacy guicey behaviour when only one instance of type is allowed (if old behaviour is important). Use uniqueItems(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[]) and GuiceyOptions.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
      • modulesOverride

        public GuiceBundle.Builder modulesOverride​(com.google.inject.Module... modules)
        Register overriding modules, used to override bindings of normal modules. Internally guice Modules.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 generic disable(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 with enableAutoConfig(String...)).

        Enables commands classpath search. All found commands are instantiated and registered in bootstrap. Default constructor is used for simple commands, but EnvironmentCommand must have constructor with Application argument.

        By default, commands search is disabled.

        Returns:
        builder instance for chained calls
        See Also:
        CommandSupport, GuiceyOptions.SearchCommands
      • noGuiceFilter

        @Deprecated
        public GuiceBundle.Builder noGuiceFilter()
        Deprecated.
        in the next version HK2 support will be removed and guice request scope will be mandatory
        Disables GuiceFilter registration for both application and admin contexts. Without guice filter registered, guice ServletModule registrations 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.

        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).

        Parameters:
        extensionClasses - extension bean classes to register
        Returns:
        builder instance for chained calls
      • extensionsOptional

        public GuiceBundle.Builder extensionsOptional​(java.lang.Class<?>... extensionClasses)
        The same as extensions(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 UniqueGuiceyBundle with correct equals implementation or implement custom deduplication logic in duplicateConfigDetector(DuplicateConfigDetector).

        Parameters:
        bundles - guicey bundles
        Returns:
        builder instance for chained calls
      • dropwizardBundles

        public GuiceBundle.Builder dropwizardBundles​(io.dropwizard.ConfiguredBundle... bundles)
        Dropwizard bundles registration. There is no difference with direct bundles registration (with Bootstrap.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 (see duplicateConfigDetector(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.TrackDropwizardBundles option.

        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 is mostly useful for testing. In some cases, it could be used to disable some extra extensions installed with classpath scan or bundle. But, generally, try to avoid manual extensions disabling for clearer application configuration.
        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 bundle GuiceyBootstrap.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 with GuiceyBootstrap.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.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 with GuiceyOptions.TrackDropwizardBundles).
        Parameters:
        bundles - guicey bundles to disable
        Returns:
        builder instance for chained calls
      • disable

        @SafeVarargs
        public final GuiceBundle.Builder disable​(java.util.function.Predicate<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.

        Use Predicate.and(Predicate), Predicate.or(Predicate) and Predicate.negate() to combine complex predicates from simple ones from Disables helper.

        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
      • strictScopeControl

        @Deprecated
        public GuiceBundle.Builder strictScopeControl()
        Deprecated.
        in the next version HK2 support will be removed and option will become useless
        Enables strict control of beans instantiation context: all beans must be instantiated by guice, except beans annotated with JerseyManaged. 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).

        Returns:
        builder instance for chained calls
        See Also:
        HK2DebugBundle
      • useHK2ForJerseyExtensions

        @Deprecated
        public GuiceBundle.Builder useHK2ForJerseyExtensions()
        Deprecated.
        in the next version HK2 support will be removed
        Manage jersey extensions (resources, jersey filters etc.) with HK2 by default instead of guice (the same effect as if JerseyManaged annotation 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!

        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 ConfigurationDiagnostic directly.

        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
      • 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. Use printCustomConfigurationBindings() 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 as printConfigurationBindings(), 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
      • 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 use printGuiceAopMap(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
      • 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 as printLifecyclePhases(), 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 guice ServletModule declarations.

        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
      • 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 name
        hook - hook class to alias
        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 access 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 needы (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