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

  1. XML Configuration
    • Commonly used but less favored in modern applications.
  2. Java Configuration
    • Preferred for its readability and type safety.
  3. Annotation-based Configuration
    • Uses annotations for configuration, making code cleaner.
  4. 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

  1. @Configuration: Indicates that the class can be used by the Spring IoC container as a source of bean definitions.
  2. @Bean: Indicates that a method produces a bean to be managed by the Spring container.
  3. @Component: Indicates that a class is a Spring-managed component.
  4. @Autowired: Allows Spring to resolve and inject collaborating beans into your bean.
  5. @Qualifier: Used to avoid confusion when multiple beans of the same type are present.
  6. @PropertySource: Specifies the location of properties files to be loaded.
  7. @Value: Used to inject property values into fields.
  8. @Profile: Indicates that a component is eligible for registration when one or more specified profiles are active.
  9. @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.