Posted on: January 18, 2025 Posted by: rahulgite Comments: 0

Spring Framework: Concepts and Examples

1. What is Spring Framework?

Spring is an open-source Java framework that provides comprehensive infrastructure support for developing enterprise applications. It is lightweight and supports modularity, allowing developers to build robust applications with loosely coupled components.


2. History of Spring

  • 2002: Introduced by Rod Johnson as part of his book “Expert One-on-One J2EE Design and Development.”
  • 2003: First version released as Spring Framework.
  • 2004: Official release of Spring 1.0.
  • Since then, Spring has evolved to support modern practices like microservices, cloud computing, and reactive programming.

3. Key Concepts

Dependency Injection (DI)

Dependency Injection is a design pattern used to achieve Inversion of Control (IoC). It decouples components by providing their dependencies from an external source rather than allowing the component to create them.

Inversion of Control (IoC)

IoC is a principle where the control of object creation and dependency management is shifted from the application to a container (like the Spring IoC container).

Spring and JEE

Spring complements Java EE (JEE) by providing additional features and simplifying enterprise development. It offers alternatives to cumbersome Java EE components like EJBs and integrates seamlessly with Java EE technologies.


4. Spring Modules

  1. Core Container: Includes Beans, Context, and Core modules.
  2. AOP (Aspect-Oriented Programming): Adds cross-cutting concerns like logging, security.
  3. Data Access/Integration: Modules like JDBC, ORM, and Transactions.
  4. Web: Supports web applications with modules like Spring MVC.
  5. Spring Boot: Simplifies configuration for standalone applications.
  6. Spring Security: Provides authentication and authorization mechanisms.
  7. Spring Batch: Handles batch processing tasks such as ETL.
  8. Spring Cloud: Simplifies building microservices and distributed systems.

5. IoC Container

Steps in IoC Lifecycle:

  1. Instantiate container (e.g., ClassPathXmlApplicationContext).
  2. Define bean configuration (XML or annotations).
  3. Container manages the lifecycle and dependency injection.

IoC Lifecycle Phases:

  1. Bean instantiation.
  2. Dependency injection.
  3. Post-initialization (@PostConstruct or custom init methods).
  4. Bean destruction (@PreDestroy or custom destroy methods).

6. Application Context and Types

ApplicationContext is the central interface in Spring for managing the application lifecycle.

Types of ApplicationContext:

  1. ClassPathXmlApplicationContext: Loads configuration from the classpath.
  2. FileSystemXmlApplicationContext: Loads configuration from the file system.
  3. AnnotationConfigApplicationContext: Loads configuration from Java-based annotations.

7. Dependency Injection in IoC

Types of DI:

  1. Constructor Injection:
<bean id="example" class="com.example.Class">
    <constructor-arg name="dependency" ref="dependencyBean" />
</bean>
  1. Setter Injection:
<bean id="example" class="com.example.Class">
    <property name="dependency" ref="dependencyBean" />
</bean>
  1. Field Injection (with annotations):
@Autowired
private Dependency dependency;

Supported Data Types:

  • Primitive types (int, String, etc.).
  • Collection types (List, Set, Map).

8. Lifecycle Methods

Spring provides lifecycle callbacks for beans:

  1. Initialization:
    • @PostConstruct
    • <bean init-method="initMethod"> (XML).
  2. Destruction:
    • @PreDestroy
    • <bean destroy-method="destroyMethod"> (XML).

Example:

public class MyBean {
    @PostConstruct
    public void init() {
        System.out.println("Bean is initialized");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("Bean is destroyed");
    }
}

9. Autowiring in Spring

Types of Autowiring:

  1. ByType: Automatically wires beans by matching types.
<bean id="example" autowire="byType" />
  1. ByName: Wires by matching property names with bean IDs.
<bean id="example" autowire="byName" />
  1. Constructor: Wires dependencies using constructor arguments.
  2. Annotations (@Autowired):
    • Automatically wires beans by type.
    • Use @Qualifier for precise control.
    @Autowired @Qualifier("specificBean") private Dependency dependency;

10. Bean Scopes

Supported Scopes:

  1. singleton (Default): A single instance per Spring container.
  2. prototype: A new instance for each request.
  3. request, session, globalSession (for web apps).

Example:

@Component
@Scope("prototype")
public class PrototypeBean {}

11. Qualifier and Primary

Qualifier:

Specifies which bean to use when multiple candidates exist.

@Autowired
@Qualifier("specificBean")
private Dependency dependency;

Primary:

Defines the default bean.

@Primary
@Bean
public UserService defaultUserService() {
    return new DefaultUserService();
}

12. Examples

Basic XML Configuration:

<beans>
    <bean id="example" class="com.example.Class">
        <property name="dependency" ref="dependencyBean" />
    </bean>
</beans>

Annotation-Based Configuration:

@Configuration
@ComponentScan("com.example")
public class AppConfig {

    @Bean
    public Dependency dependencyBean() {
        return new Dependency();
    }
}

Spring Boot Application Example:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Leave a Comment