mirror of
https://github.com/google/guice.git
synced 2024-04-21 12:32:36 +00:00
Page:
InjectOnlyDirectDependencies
Pages
3rdPartyModules
AOP
AppsThatUseGuice
AssistedInject
Avoid Injecting Closable Resources
AvoidCallingProvideMethodsAndInjectConstructors
AvoidConditionalLogicInModules
AvoidStaticState
BeCarefulAboutIoInProviders
BestPractices
BindingAnnotations
BindingResolution
Bindings
Bootstrap
BoundFields
BuiltInBindings
ClassLoading
CustomInjections
CustomScopes
CyclicDependencies
DocumentPublicBindings
DontReuseAnnotations
Errors
ExtendingGuice
ExtensionSPI
ExternalDocumentation
FrequentlyAskedQuestions
GettingStarted
GoogleAppEngine
Grapher
Guice10
Guice20
Guice30
Guice40
Guice41
Guice42
Guice421
Guice422
Guice423
Guice500
Guice501
Guice510
Guice600
Guice700
GuiceDiscussions
GuiceInKotlin
GuicePersist
GuicePersistMultiModules
Home
InjectOnlyDirectDependencies
InjectingProviders
InjectingTheInjector
InjectionPoints
Injections
InspectingModules
InstanceBindings
JPA
JSR330
JustInTimeBindings
KeepConstructorsHidden
LinkedBindings
MentalModel
MinimizeMutability
ModulesShouldBeFastAndSideEffectFree
Motivation
Multibindings
OSGi
OptionalAOP
OrganizeModulesByFeature
PreferAtProvides
ProviderBindings
ProvidesMethods
RestrictedBindingSource
Scopes
ServletExtensionSPI
ServletModule
ServletRegexKeyMapping
Servlets
SpringComparison
Struts2Integration
ThrowingProviders
ToConstructorBindings
Transactions
UntargettedBindings
UseNullable
Clone
5
InjectOnlyDirectDependencies
Copybara-Service edited this page 2020-08-06 10:09:21 -07:00
Table of Contents
Inject only direct dependencies
Avoid injecting an object only as a means to get at another object. For example,
don't inject a Customer as a means to get at an Account:
public class ShowBudgets {
private final Account account;
@Inject
ShowBudgets(Customer customer) {
account = customer.getPurchasingAccount();
}
Instead, inject the dependency directly. This makes testing easier; the test
case doesn't need to concern itself with the customer. Use an @Provides method
in your Module to create the binding for Account that uses the binding for
Customer:
public class CustomersModule extends AbstractModule {
@Override public void configure() {
...
}
@Provides
Account providePurchasingAccount(Customer customer) {
return customer.getPurchasingAccount();
}
By injecting the dependency directly, our code is simpler.
public class ShowBudgets {
private final Account account;
@Inject
ShowBudgets(Account account) {
this.account = account;
}
-
User's Guide
-
Integration
-
Extensions
-
Internals
-
Releases
-
Community