Implementing Dependency Injection

1. Implementing Constructor Injection

BenefitDetail
Required depsCannot construct without
Immutablefinal fields
TestablePass mocks directly
SpringNo annotation needed if single ctor

Example: Constructor injection

@Service
public class OrderService {
    private final OrderRepository repo;
    private final PaymentGateway gateway;
    public OrderService(OrderRepository repo, PaymentGateway gateway) {
        this.repo = repo;
        this.gateway = gateway;
    }
}

2. Implementing Setter Injection

Use CaseDetail
Optional depsMay be null
ReconfigurableChange at runtime
DrawbackMutable; risk of half-built object

3. Understanding Field Injection

AspectDetail
Syntax@Autowired private Foo foo;
ProsConcise
ConsHidden deps, hard to test, mutable DISCOURAGED

4. Implementing Component Scanning

AnnotationRole
@ComponentGeneric
@ServiceService layer
@RepositoryPersistence; exception translation
@ControllerWeb MVC
@RestControllerREST endpoints
@ConfigurationBean definitions

5. Implementing Bean Lifecycle

instantiate → populate → BeanNameAware/AppContextAware
  → @PostConstruct / InitializingBean.afterPropertiesSet
  → init-method → ready
  → @PreDestroy / DisposableBean.destroy → destroy-method
  

6. Implementing Scope Management

ScopeLifetime
singletonPer container (default)
prototypeNew per injection
requestPer HTTP request
sessionPer HTTP session
applicationPer ServletContext
websocketPer WebSocket session

7. Implementing Qualifier Annotations

Example: Disambiguate beans

@Qualifier("primaryDb")
@Service
public class PrimaryDbReader { ... }

@Service
public class ReportService {
    public ReportService(@Qualifier("primaryDb") DbReader reader) { ... }
}

8. Implementing Conditional Beans

AnnotationCondition
@ConditionalOnPropertyProperty exists/equals
@ConditionalOnMissingBeanNo matching bean
@Profile("prod")Active profile
@ConditionalOnClassClass on classpath

9. Resolving Circular Dependencies

StrategyDetail
RefactorExtract third bean
Setter injectBreak cycle (Spring)
@LazyProxy delays resolution
ApplicationEventDecouple via event
Warning: Constructor injection cycles fail at startup — usually a design smell.

10. Implementing Primary Beans

Example: Default among multiple

@Primary
@Service
public class DefaultPaymentGateway implements PaymentGateway { ... }

@Service
public class StripeGateway implements PaymentGateway { ... }
// Injection of PaymentGateway picks DefaultPaymentGateway unless @Qualifier used.

11. Implementing Custom Scopes

StepDetail
Implement ScopeOverride get, remove
RegisterCustomScopeConfigurer bean
Use@Scope("tenant")

12. Understanding Dependency Injection Containers

ContainerStyleStartup
SpringReflectionSlower; flexible
Dagger 2Compile-timeFast; verbose
MicronautCompile-time AOTVery fast
QuarkusCompile-time + nativeNative image friendly
GuiceReflectionLightweight