0% found this document useful (0 votes)
3 views6 pages

Spring Core Module Study Notes

The document provides an overview of the Spring Framework's core concepts, focusing on Spring Beans and the Inversion of Control (IoC) container that manages object creation and dependencies. It explains various dependency injection methods, stereotype annotations for bean declaration, and features of the ApplicationContext compared to BeanFactory. Additionally, it covers bean lifecycle, scopes, and annotations like @Component, @Autowired, and @Value that facilitate configuration and management of beans.

Uploaded by

764t59r4t5
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views6 pages

Spring Core Module Study Notes

The document provides an overview of the Spring Framework's core concepts, focusing on Spring Beans and the Inversion of Control (IoC) container that manages object creation and dependencies. It explains various dependency injection methods, stereotype annotations for bean declaration, and features of the ApplicationContext compared to BeanFactory. Additionally, it covers bean lifecycle, scopes, and annotations like @Component, @Autowired, and @Value that facilitate configuration and management of beans.

Uploaded by

764t59r4t5
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Spring Core Module Study Notes

Introduction to Spring Beans

A Spring Bean is essentially a Java object that is managed by the Spring Framework's Inversion
of Control (IoC) container. Unlike traditional Java where objects are created manually using the
`new` keyword, Spring automatically creates and manages these objects. To define a class as a
Spring Bean, annotations like @Component are used. When Spring starts, it creates instances
of these classes and manages their lifecycle, making them available for dependency injection
throughout the application.

Key Point: A Bean is an object created and managed by the Spring container, facilitating loose
coupling and easier management of dependencies.

Understanding the IOC Container

The core of Spring is the Inversion of Control (IoC) container, which is responsible for creating,
configuring, and managing beans. The two main types of containers are:

1.​ BeanFactory: The basic container that provides fundamental functionalities.


2.​ ApplicationContext: An advanced container with additional features like event
propagation, internationalization, and more. It is the most commonly used container in
Spring applications.

Example of initializing ApplicationContext:

ApplicationContext context = new AnnotationConfigApplicationContext([Link]);


Student s = [Link]([Link]);

This setup allows Spring to manage bean creation and dependency resolution automatically.

Inversion of Control (IoC) Concept

IoC means that the control of object creation and dependency management is transferred from
the programmer to the Spring container. In traditional Java, developers manually instantiate
objects, but with IoC, Spring handles this process, leading to more modular and testable code.

Normal Java: Programmer creates objects manually.

Spring IoC: Spring creates and manages objects, promoting loose coupling.
Dependencies and Dependency Injection (DI)

A dependency occurs when one class requires another class to function. For example, a Car
class depends on an Engine.

class Car {
Engine engine;
}

Spring simplifies dependency management through Dependency Injection, where it


automatically injects required dependencies into classes. This can be done via constructor,
setter, or field injection.

Types of Dependency Injection

1.​ Constructor Injection: Dependencies are provided through class constructors. Ideal for
mandatory dependencies.
2.​ class Car { Engine engine; Car(Engine engine){ [Link] =
engine; } }
3.​ Setter Injection: Dependencies are injected via setter methods. Suitable for optional
dependencies.
4.​ class Car { Engine engine; public void setEngine(Engine engine){
[Link] = engine; } }
5.​ Field Injection: Dependencies are injected directly into class variables using
annotations like @Autowired. Not recommended for production due to poor testability.
6.​ @Autowired Engine engine;

Spring also supports arbitrary method injection, where dependencies are injected through any
method, but this is rarely used.

Stereotype Annotations for Bean Declaration

Annotations like @Component, @Service, @Repository, and @Controller mark classes as


Spring Beans for different layers of an application:

●​ @Component: Generic bean marker.


●​ @Service: Business logic layer.
●​ @Repository: Data access layer.
●​ @Controller: Web layer (Spring MVC).

Example:

@Service
public class UserService {
}

Dependency Injection Annotations

@Autowired

Automatically injects dependencies into fields, constructors, or methods.

@Autowired
Engine engine;

@Value

Injects simple values or values from properties files.

@Value("Prashant")
String name;

Or from properties:

@Value("${[Link]}")

Component Scanning and Property Management

@ComponentScan

Instructs Spring to scan specified packages for components and beans.

@ComponentScan("[Link]")

@PropertySource

Loads properties files into the Spring environment.

@PropertySource("classpath:[Link]")

Bean Configuration and Management

@Configuration and @Bean

Defines configuration classes and beans within them:

@Configuration
public class AppConfig {
@Bean
public Engine engine() {
return new Engine();
}
}

@Primary and @Qualifier

Handle multiple beans of the same type:

●​ @Primary: Sets default bean when multiple beans exist.


●​ @Qualifier: Specifies which bean to inject.

@Autowired
@Qualifier("dieselEngine")
Engine engine;

XML Configuration Import


@ImportResource("[Link]")

This allows importing traditional XML bean definitions into Java config.

Bean Scope and Lifecycle

ScopeMeaningsingletonOne shared instance (default)prototypeNew instance each


timerequestOne per HTTP requestsessionOne per user sessionapplicationOne per web
applicationwebsocketPer WebSocket connection

@Scope("prototype")

@Lazy

Creates beans only when they are first needed, improving startup performance.

@Lazy
@Component
class Car {}

Spring Bean Lifecycle

Beans go through several stages:

1.​ Creation: Object instantiated by Spring.


2.​ Dependency Injection: Dependencies are injected.
3.​ Initialization: Custom init methods run, e.g., @PostConstruct.
4.​ Ready for use: Bean is fully initialized.
5.​ Destruction: Cleanup via @PreDestroy.
ApplicationContext Features

Compared to BeanFactory, ApplicationContext offers:

●​ Pre-instantiation of singleton beans


●​ Support for annotations
●​ Properties file support
●​ Internationalization (i18n)
●​ Event handling
●​ Ability to close the container

Quick Interview Summary


**Concept:**
In the context of Spring Framework, the core idea revolves around managing the lifecycle and
dependencies of objects within an application. This is achieved through a comprehensive
Inversion of Control (IoC) container that handles the creation, configuration, and management of
objects, often referred to as beans.

**Simple Meaning:**
At its simplest, Spring provides a way to manage objects—called beans—by controlling their
instantiation and dependencies automatically, reducing the need for manual object creation and
wiring.

**Bean:**
A bean is essentially an object that is managed by the Spring IoC container. These beans are
created, configured, and maintained by Spring, allowing developers to focus on business logic
rather than object lifecycle management.

**Object Managed by Spring IoC:**


When we say that an object is managed by Spring IoC, it means that Spring takes responsibility
for creating the object, injecting its dependencies, and managing its lifecycle throughout the
application's runtime.

**Spring Controls Object Creation:**


Spring's IoC container is responsible for instantiating objects based on configuration metadata,
such as annotations or XML files. This process ensures that objects are created in a consistent
manner, with all necessary dependencies properly injected.

**Spring Injects Dependencies:**


One of the key features of Spring is dependency injection, where the framework automatically
supplies the required dependencies to an object, rather than the object creating or looking up its
dependencies itself. This promotes loose coupling and easier testing.
**@Component:**
This annotation is used to mark a class as a Spring-managed bean. When a class is annotated
with @Component, Spring automatically detects it during component scanning and registers it
as a bean within the application context.

**@Autowired:**
This annotation is used to inject dependencies into a bean. When placed on a field, constructor,
or setter method, Spring automatically wires the appropriate bean into that location, based on
type or qualifier.

**@Value:**
The @Value annotation is used to inject simple values, such as strings, numbers, or other
primitive data types, into a bean's property. It allows for externalized configuration, such as
values from properties files.

**@Bean:**
This annotation is used within a configuration class to explicitly define a bean. Methods
annotated with @Bean produce a bean that is managed by Spring, allowing for custom
configuration and instantiation logic.

**@Scope:**
The @Scope annotation defines the lifecycle scope of a bean. Common scopes include
singleton (default, one shared instance), prototype (a new instance each time), request,
session, and application scopes, depending on the application's needs.

**@Lazy:**
The @Lazy annotation indicates that a bean should be created only when it is first needed,
rather than at application startup. This can improve startup time and resource utilization by
delaying bean creation until necessary. ---

You might also like