### Apache License 2.0 Boilerplate Notice Source: https://github.com/square/dagger/blob/master/LICENSE.txt Standard boilerplate notice to be attached to works to apply the Apache License, Version 2.0. Fields enclosed in brackets `[]` should be replaced with specific identifying information. It is recommended to include a file or class name and purpose description alongside the notice for easier identification. ```text Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` -------------------------------- ### Lazy Injections in Dagger Source: https://github.com/square/dagger/blob/master/website/index.html Illustrates the use of Lazy to defer the instantiation of an object until its get() method is first called. Subsequent calls to get() on the same Lazy instance will return the same underlying object. ```Java class GridingCoffeeMaker { @Inject Lazy lazyGrinder; public void brew() { while (needsGrinding()) { // Grinder created once on first call to .get() and cached. lazyGrinder.get().grind(); } } } ``` -------------------------------- ### Java: Grouping @Provides Methods in a Dagger Module Source: https://github.com/square/dagger/blob/master/website/index.html Explains that all @Provides methods must be contained within a class annotated with @Module. This example shows a DripCoffeeModule grouping several @Provides methods, organizing the dependency provision logic. ```Java @Module class DripCoffeeModule { @Provides Heater provideHeater() { return new ElectricHeater(); } @Provides Pump providePump(Thermosiphon pump) { return pump; } } ``` -------------------------------- ### Building the Dagger Object Graph and Bootstrapping Injection Source: https://github.com/square/dagger/blob/master/website/index.html Demonstrates how to create the Dagger ObjectGraph by passing modules and how to bootstrap injection by registering the main application class with the graph to obtain an injected instance. ```Java ObjectGraph objectGraph = ObjectGraph.create(new DripCoffeeModule()); ``` ```Java class CoffeeApp implements Runnable { @Inject CoffeeMaker coffeeMaker; @Override public void run() { coffeeMaker.brew(); } public static void main(String[] args) { ObjectGraph objectGraph = ObjectGraph.create(new DripCoffeeModule()); CoffeeApp coffeeApp = objectGraph.get(CoffeeApp.class); ... } } ``` ```Java @Module( injects = CoffeeApp.class ) class DripCoffeeModule { ... } ``` -------------------------------- ### Initialize Dagger Documentation Page UI and Analytics Source: https://github.com/square/dagger/blob/master/website/index.html This JavaScript code initializes various client-side functionalities for the Dagger documentation page. It includes syntax highlighting using `prettyPrint()`, scroll spying for navigation, smooth scrolling for internal links, and tooltips for menu items. Additionally, it dynamically fetches and displays the latest versions of Dagger and Dagger Compiler artifacts and integrates Google Analytics for page view tracking. ```JavaScript $(function() { // Syntax highlight code blocks. prettyPrint(); // Spy on scroll position for real-time updating of current section. $('body').scrollspy(); // Use smooth-scroll for internal links. $('a').smoothScroll(); // Enable tooltips on the header nav image items. $('.menu').tooltip({ placement: 'bottom', trigger: 'hover', container: 'body', delay: { show: 500, hide: 0 } }); // Look up the latest version of the library. $.fn.artifactVersion('com.squareup.dagger', 'dagger', function(version, url) { $('.version').text(version); $('.version-tag').text('v' + version); $('.core-version-href').attr('href', url); }); $.fn.artifactVersion('com.squareup.dagger', 'dagger-compiler', function(version, url) { $('.compiler-version-href').attr('href', url); }); }); var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-40704740-3']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); ``` -------------------------------- ### Providing Qualified Dependencies with Dagger @Provides Source: https://github.com/square/dagger/blob/master/website/index.html Shows how to annotate @Provides methods with qualifier annotations to supply specific instances for qualified injection points. Each method provides a distinct Heater instance identified by its @Named qualifier. ```Java @Provides @Named("hot plate") Heater provideHotPlateHeater() { return new ElectricHeater(70); } @Provides @Named("water") Heater provideWaterHeater() { return new ElectricHeater(93); } ``` -------------------------------- ### Implementing Singletons with Dagger Source: https://github.com/square/dagger/blob/master/website/index.html Explains how to use the @Singleton annotation on @Provides methods or injectable classes to ensure that the Dagger graph provides a single instance of a value to all its clients. This also serves as documentation for potential maintainers. ```Java @Provides @Singleton Heater provideHeater() { return new ElectricHeater(); } ``` ```Java @Singleton class CoffeeMaker { ... } ``` -------------------------------- ### Configure Maven Dependencies for Dagger 1 Source: https://github.com/square/dagger/blob/master/README.md This XML snippet demonstrates how to include Dagger 1 runtime and compiler dependencies in a Maven `pom.xml` file. The `dagger` artifact is for runtime, and `dagger-compiler` is for compile-time code generation, typically marked as optional or provided. ```XML com.squareup.dagger dagger ${dagger.version} com.squareup.dagger dagger-compiler ${dagger.version} true ``` -------------------------------- ### Java: Providing Dependencies with Internal Dependencies in Dagger Source: https://github.com/square/dagger/blob/master/website/index.html Demonstrates that @Provides methods can themselves have dependencies. Dagger will resolve these internal dependencies before invoking the @Provides method to create the requested instance. ```Java @Provides Pump providePump(Thermosiphon pump) { return pump; } ``` -------------------------------- ### Java: Injecting Dependencies via Constructor in Dagger Source: https://github.com/square/dagger/blob/master/website/index.html Demonstrates how to use the @Inject annotation on a constructor. Dagger will use this constructor to create instances of the class, automatically resolving and providing the required parameters. ```Java class Thermosiphon implements Pump { private final Heater heater; @Inject Thermosiphon(Heater heater) { this.heater = heater; } ... } ``` -------------------------------- ### Java: Providing Dependencies for Interfaces or Third-Party Classes in Dagger Source: https://github.com/square/dagger/blob/master/website/index.html Shows how to use an @Provides-annotated method to satisfy dependencies for types that cannot be constructed directly by Dagger (e.g., interfaces, third-party classes, or configurable objects). The method's return type defines the dependency it satisfies. ```Java @Provides Heater provideHeater() { return new ElectricHeater(); } ``` -------------------------------- ### Provider Injections in Dagger Source: https://github.com/square/dagger/blob/master/website/index.html Describes how to inject a Provider to obtain multiple instances of a type, where each call to Provider.get() creates a new instance of T. A note is included regarding potential design implications of using Provider. ```Java class BigCoffeeMaker { @Inject Provider filterProvider; public void brew(int numberOfPots) { ... for (int p = 0; p < numberOfPots; p++) { maker.addFilter(filterProvider.get()); //new filter every time. maker.addCoffee(...); maker.percolate(); ... } } } ``` -------------------------------- ### Injecting Qualified Dependencies in Dagger Source: https://github.com/square/dagger/blob/master/website/index.html Demonstrates how to apply qualifier annotations like @Named to fields that are injected by Dagger. This allows for injecting different instances of the same type based on their qualifier. ```Java class ExpensiveCoffeeMaker { @Inject @Named("water") Heater waterHeater; @Inject @Named("hot plate") Heater hotPlateHeater; ... } ``` -------------------------------- ### Add Dagger Dependencies to Maven Project Source: https://github.com/square/dagger/blob/master/website/index.html This XML snippet shows the necessary Maven dependencies for including Dagger in a project. It specifies the core Dagger JAR for runtime and the Dagger compiler JAR for compile-time code generation, with the compiler being optional. ```XML com.squareup.dagger dagger _(insert latest version)_ com.squareup.dagger dagger-compiler _(insert latest version)_ true ``` -------------------------------- ### Declare a Dagger Module as Incomplete Source: https://github.com/square/dagger/blob/master/website/index.html Illustrates how to mark a Dagger module as complete = false to allow it to have missing dependencies without causing a compile-time error. This is useful for partial graphs or testing. ```Java @Module(complete = false) class DripCoffeeModule { @Provides Heater provideHeater(Executor executor) { return new CpuHeater(executor); } } ``` -------------------------------- ### Java: Injecting Dependencies via Fields in Dagger Source: https://github.com/square/dagger/blob/master/website/index.html Illustrates how Dagger can directly inject dependencies into fields annotated with @Inject. Dagger obtains the necessary instances and assigns them to the respective fields. ```Java class CoffeeMaker { @Inject Heater heater; @Inject Pump pump; ... } ``` -------------------------------- ### Dagger Compile-time Error: Unused @Provider Methods Source: https://github.com/square/dagger/blob/master/website/index.html Displays the javac error message indicating that Dagger's annotation processor has found unused @Provides methods in a module, prompting the developer to either use the binding or mark the module as a library. ```Text [ERROR] COMPILATION ERROR: [ERROR]: Graph validation failed: You have these unused @Provider methods: 1. coffee.DripCoffeeModule.provideChiller() Set library=true in your module to disable this check. ``` -------------------------------- ### Execute Static Injection using Dagger ObjectGraph Source: https://github.com/square/dagger/blob/master/website/index.html Illustrates how to trigger static injection using ObjectGraph.injectStatics(). This method populates static fields annotated with @Inject in classes specified in the module's staticInjections. ```Java ObjectGraph objectGraph = ObjectGraph.create(new LegacyModule()); objectGraph.injectStatics(); ``` -------------------------------- ### Override Dagger Module Bindings for Testing with JUnit and Mockito Source: https://github.com/square/dagger/blob/master/website/index.html This Java JUnit test demonstrates how to use Dagger's `overrides = true` feature in a module to replace a production binding (Heater) with a Mockito mock. It shows injecting the mock into the `CoffeeMaker` and the test class, then verifying interactions with the mocked dependency. ```Java public class CoffeeMakerTest { @Inject CoffeeMaker coffeeMaker; @Inject Heater heater; @Before public void setUp() { ObjectGraph.create(new TestModule()).inject(this); } @Module( includes = DripCoffeeModule.class, injects = CoffeeMakerTest.class, overrides = true ) static class TestModule { @Provides @Singleton Heater provideHeater() { return Mockito.mock(Heater.class); } } @Test public void testHeaterIsTurnedOnAndThenOff() { Mockito.when(heater.isHot()).thenReturn(true); coffeeMaker.brew(); Mockito.verify(heater, Mockito.times(1)).on(); Mockito.verify(heater, Mockito.times(1)).off(); } } ``` -------------------------------- ### Aggregate Dagger Modules with @Module includes Source: https://github.com/square/dagger/blob/master/website/index.html Demonstrates how to use the includes attribute in a Dagger @Module annotation to combine multiple modules into a single application graph. This enables cross-module validation by the annotation processor. ```Java @Module( includes = { DripCoffeeModule.class, ExecutorModule.class } ) public class CoffeeAppModule { } ``` -------------------------------- ### Dagger Module with Unused @Provides Method (Error) Source: https://github.com/square/dagger/blob/master/website/index.html Presents a Dagger module where a @Provides method (provideChiller) is defined but its provided type is not used by any of the injects classes, leading to a compile-time error. ```Java @Module(injects = Example.class) class DripCoffeeModule { @Provides Heater provideHeater() { return new ElectricHeater(); } @Provides Chiller provideChiller() { return new ElectricChiller(); } } ``` -------------------------------- ### Dagger Compile-time Error: No Binding Found Source: https://github.com/square/dagger/blob/master/website/index.html Shows the javac error message generated when Dagger's annotation processor detects a missing binding for a required dependency, such as java.util.concurrent.Executor. ```Text [ERROR] COMPILATION ERROR : [ERROR] error: No binding for java.util.concurrent.Executor required by provideHeater(java.util.concurrent.Executor) ``` -------------------------------- ### Dagger Module Missing Dependency Binding (Error) Source: https://github.com/square/dagger/blob/master/website/index.html Demonstrates a Dagger module that will cause a compile-time error due to a missing binding for Executor. The annotation processor strictly validates all dependencies. ```Java @Module class DripCoffeeModule { @Provides Heater provideHeater(Executor executor) { return new CpuHeater(executor); } } ``` -------------------------------- ### Mark a Dagger Module as a Library Source: https://github.com/square/dagger/blob/master/website/index.html Shows how to set library = true in a Dagger @Module annotation. This disables the check for unused @Provides methods, allowing the module to provide types that might be consumed by other modules or external components. ```Java @Module( injects = Example.class, library = true ) class DripCoffeeModule { @Provides Heater provideHeater() { return new ElectricHeater(); } @Provides Chiller provideChiller() { return new ElectricChiller(); } } ``` -------------------------------- ### Configure Static Field Injection in Dagger Modules Source: https://github.com/square/dagger/blob/master/website/index.html Explains how to enable static field injection for a class by listing it in the staticInjections attribute of a Dagger @Module annotation. This allows Dagger to inject dependencies into static fields. ```Java @Module( staticInjections = LegacyCoffeeUtils.class ) class LegacyModule { } ``` -------------------------------- ### Define a Custom Qualifier Annotation in Dagger Source: https://github.com/square/dagger/blob/master/website/index.html Illustrates the declaration of a custom qualifier annotation, such as @Named from javax.inject, which is used to distinguish between dependencies of the same type. It shows the required @Qualifier meta-annotation and retention policies. ```Java @Qualifier @Documented @Retention(RUNTIME) public @interface Named { String value() default ""; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.