SPRING FRAMEWORK & SPRING BOOT NOTES (For AKTU Java Exam)
PART 1: SPRING FRAMEWORK - CORE BASICS
1. Spring Dependency Injection (DI)
Definition: Dependency Injection (DI) is a design pattern used to remove dependency creation from
application code and delegate it to the Spring container. It promotes loose coupling and enhances
modularity.
Uses: - Encourages modular and testable code - Easier to manage and refactor dependencies - Reduces
tight coupling between components
Types of Dependency Injection: 1. Constructor Injection - Dependencies are provided through the class
constructor. 2. Setter Injection - Dependencies are provided through public setter methods. 3. Field
Injection - Dependencies are directly injected into fields using annotations.
Example 1: Constructor Injection
@Component
public class Student {
private final Address address;
@Autowired
public Student(Address address) {
[Link] = address;
}
}
Example 2: Setter Injection
@Component
public class Student {
private Address address;
@Autowired
public void setAddress(Address address) {
[Link] = address;
}
}
1
Example 3: Field Injection
@Component
public class Student {
@Autowired
private Address address;
}
How it's implemented: - Annotate dependencies with @Autowired - Use @ComponentScan to detect
annotated classes - Prefer constructor injection for immutability and testability
2. Spring Inversion of Control (IoC)
Definition: IoC is a programming principle where the control of object creation and dependency
management is transferred to the Spring container.
Uses: - Manages object lifecycles automatically - Enables easy configuration and testing
IoC Containers: 1. BeanFactory - Provides basic DI support 2. ApplicationContext - Extends BeanFactory
with more features (AOP, event propagation)
Example 1: XML Configuration
<beans>
<bean id="myBean" class="[Link]"/>
</beans>
Example 2: Java Configuration
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
How it's implemented: - Define beans using XML, Java config, or annotations - Spring creates and manages
these beans at runtime
2
3. Aspect-Oriented Programming (AOP)
Definition: AOP is a programming paradigm that allows separation of cross-cutting concerns like logging,
transactions, and security.
Uses: - Enhances modularity - Eliminates code duplication
Key AOP Concepts: - Aspect: Module containing cross-cutting concern - Advice: Action taken at a join point
- Join Point: A point in application execution (e.g., method call) - Pointcut: Predicate that matches join
points - Weaving: Linking aspects with application code
Example 1: Before Advice
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* [Link].*.*(..))")
public void logBefore() {
[Link]("Before method execution");
}
}
Example 2: Around Advice
@Aspect
@Component
public class PerformanceAspect {
@Around("execution(* [Link].*.*(..))")
public Object measureTime(ProceedingJoinPoint joinPoint) throws Throwable {
long start = [Link]();
Object result = [Link]();
long end = [Link]();
[Link]("Execution Time: " + (end - start) + "ms");
return result;
}
}
How it's implemented: - Enable AOP via Spring configuration - Use @Aspect and advice annotations like
@Before , @Around
4. Bean Scopes
Definition: Defines the lifecycle and visibility of a bean in the Spring container.
3
Uses: - Optimize memory usage - Suit beans to specific application needs (stateless, stateful)
Types of Bean Scopes with Examples: | Scope | Description | Example Code | Use Case |
|-------------|-------------------------------------------------|--------------|----------| | Singleton | Single instance per Spring
container | @Component @Scope("singleton") | Stateless service class | | Prototype | New instance
each time requested | @Component @Scope("prototype") | Stateful objects like form inputs | |
Request | New instance per HTTP request | @Component @Scope(value =
WebApplicationContext.SCOPE_REQUEST) | Beans tied to a web request | | Session | New instance
per HTTP session | @Component @Scope(value = WebApplicationContext.SCOPE_SESSION) |
Track user-specific data | | Application | One instance per web application |
@Component @Scope(value = WebApplicationContext.SCOPE_APPLICATION) | Shared data across
the app | | WebSocket | One instance per WebSocket session | @Component @Scope(scopeName =
"websocket", proxyMode = ScopedProxyMode.TARGET_CLASS) | WebSocket communication |
Example Usage: - Singleton: A service class reused across all users. - Prototype: Each user form creates a
new bean instance. - Request: A bean created for each incoming web request. - Session: Shopping cart data
stored per session. - Application: Global counters like hit count. - WebSocket: Real-time chat session data
per connection.
How it's implemented: - Use @Scope("scopeName") or Web-specific constants - Ensure web-related
scopes have proper context setup in Spring MVC or Boot
5. Autowiring
Definition: Spring’s feature for automatically injecting dependencies by scanning the application context.
Uses: - Minimizes boilerplate code - Simplifies configuration
Autowiring Modes: - byType – Injects bean by matching data type - byName – Injects bean by matching
property name - constructor – Injects dependencies using constructor
Example 1: Field Injection
@Component
public class OrderService {
@Autowired
private PaymentService paymentService;
}
Example 2: Qualifier
4
@Autowired
@Qualifier("paypalService")
private PaymentService service;
How it's implemented: - Add @Autowired annotation - Use @Qualifier to avoid ambiguity if multiple
beans of the same type exist
6. Common Spring Annotations
Definition: Annotations in Spring Framework provide metadata that instructs the container on how to
behave and configure beans.
Uses: - Reduces XML configuration - Enhances code readability
Important Annotations: - @Component – Marks class as bean - @Service – Business logic class -
@Repository – Persistence layer - @Controller – Web controller - @Autowired – Enables DI -
@Qualifier – Specifies exact bean - @Scope – Defines bean lifecycle - @Bean – Defines method-level
bean - @Configuration – Declares Java config class
Example 1:
@Component
public class EmailService {}
Example 2:
@Configuration
public class AppConfig {
@Bean
public EmailService emailService() {
return new EmailService();
}
}
7. Bean Lifecycle Callbacks
Definition: Hooks provided by Spring to perform custom actions during a bean’s lifecycle events.
Uses: - Initialization and cleanup logic - Resource handling
5
Annotations Used: - @PostConstruct – Called after bean initialization - @PreDestroy – Called before
bean destruction
Example 1: Initialization
@PostConstruct
public void init() {
[Link]("Bean initialized");
}
Example 2: Destruction
@PreDestroy
public void destroy() {
[Link]("Bean is being destroyed");
}
How it's implemented: - Annotate methods with @PostConstruct and @PreDestroy - Requires
[Link] or [Link] packages
(Continued in Part 2: Spring Boot...)