Coconote
AI notes
AI voice & video notes
Try for free
Understanding Dependency Injection in Spring
Sep 20, 2024
Notes on Dependency Injection and Spring Framework
Introduction
Overview of Dependency Injection (DI)
Definition of DI
Importance of DI in Spring Framework
Types of Dependency Injection
XML Configuration
Commonly used but less favored in modern applications.
Java Configuration
Preferred for its readability and type safety.
Annotation-based Configuration
Uses annotations for configuration, making code cleaner.
Combined Configuration
Utilizes XML, Java, and annotations together.
Configuration in Spring
How to configure DI in Spring:
Using XML
Using Java Config
Using Annotations
Important Concepts in Spring
Bean Scopes
Singleton
: One instance per Spring container.
Prototype
: New instance each time requested.
Request
: One instance per HTTP request (web applications).
Session
: One instance per HTTP session (web applications).
Global Session
: Used in portlet applications.
Application
: One instance per application context.
Loading Properties Files
How to load properties files using:
Spring Environment object.
@Value
annotation.
@PropertySource
annotation.
Profiles in Spring
Profiles allow configuration files to change based on environment (dev, test, prod).
Use
@Profile
annotation alongside properties files.
Configuration can be switched using
spring.profiles.active
.
Spring Annotations Recap
@Configuration
: Indicates that the class can be used by the Spring IoC container as a source of bean definitions.
@Bean
: Indicates that a method produces a bean to be managed by the Spring container.
@Component
: Indicates that a class is a Spring-managed component.
@Autowired
: Allows Spring to resolve and inject collaborating beans into your bean.
@Qualifier
: Used to avoid confusion when multiple beans of the same type are present.
@PropertySource
: Specifies the location of properties files to be loaded.
@Value
: Used to inject property values into fields.
@Profile
: Indicates that a component is eligible for registration when one or more specified profiles are active.
@Lazy
: Indicates that a bean should be initialized lazily.
Summary of Key Points
Dependency Injection is crucial in decoupling application components.
Spring Framework provides various means of configuring DI, including XML, Java, and annotations.
Understanding scopes, properties, and profiles is essential for effective Spring application development.
📄
Full transcript