0% found this document useful (0 votes)
29 views9 pages

Spring Framework & Boot Study Notes

Spring boot framework in java
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)
29 views9 pages

Spring Framework & Boot Study Notes

Spring boot framework in java
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

Comprehensive Spring Framework and Spring Boot Study Notes for Exam

Preparation
This document consolidates all the information provided across previous prompts and search
results into a structured, detailed set of notes for studying the Spring Framework and Spring
Boot during exam preparation. It covers core concepts, practical examples, and key
components in a clear, organized manner.

Spring Framework Overview


Introduction:
Spring is an open-source, lightweight Java framework released in 2003 under the
Apache 2.0 license, developed by Rod Johnson [1] [2] .
Known as a "framework of frameworks," it supports integration with Struts, Hibernate,
EJB, JSF, and others [2] .
Used for building both standalone and enterprise applications [1] .
Comprises modules like IOC, AOP, DAO, Context, ORM, and Web MVC [2] .

Advantages:
Modular and Lightweight: Allows selective use of components; based on POJO
implementation, non-invasive as it doesn’t force inheritance or interface implementation
[1] [2] .

Flexible Configuration: Supports XML, Java, and annotation-based configurations [1] .


Dependency Injection (DI): Promotes loose coupling by injecting dependencies [1] [2] .
Aspect-Oriented Programming (AOP): Manages cross-cutting concerns like logging
and security [1] .
Simplified Database Access: Provides JDBC templates and abstractions [1] .
Testing Support: Facilitates unit testing without server dependency [1] .

Security Module: Built-in security features [1] .


Integration and Scalability: Seamless integration with other frameworks and support
for scalable applications [1] .
Fast Development: DI and framework support accelerate JavaEE development [2] .

Powerful Abstraction: Abstracts JavaEE specifications like JMS, JDBC, JPA, and JTA
[2] .
Core Concepts of Spring Framework

Inversion of Control (IoC) and Dependency Injection (DI)


Inversion of Control (IoC):
A design principle where control of object creation and dependency resolution is
transferred from application code to the Spring container [1] [2] .
Achieved primarily through Dependency Injection, promoting modularity, testability, and
maintainability [1] .
Example of Tight vs. Loose Coupling [2] :

// Tight Coupling (Without IoC)


class Employee {
Address address;
Employee() {
address = new Address(); // Hard-coded dependency
}
}
// Loose Coupling (With IoC)
class Employee {
Address address;
Employee(Address address) {
[Link] = address; // Dependency injected
}
}

Dependency Injection (DI):


A design pattern to remove dependencies from code, achieving loose coupling [1] [2] .

Spring IoC container injects dependencies using metadata from XML or annotations [2] .
Types of DI:
Constructor Injection: Dependencies injected via constructor; ensures immutability
and required dependencies [1] .
Example (Primitive Values) [1] :

package [Link];
public class Employee {
private int id;
private String name;
public Employee(int id, String name) {
[Link] = id;
[Link] = name;
}
void show() {
[Link](id + " " + name);
}
}

XML Configuration [1] :


<bean id="e" class="[Link]">
<constructor-arg value="10" type="int"></constructor-arg>
<constructor-arg value="Sonoo"></constructor-arg>
</bean>

Example (Dependent Object) [1] :

package [Link];
public class Employee {
private int id;
private String name;
private Address address; // Aggregation
public Employee(int id, String name, Address address) {
[Link] = id;
[Link] = name;
[Link] = address;
}
void show() {
[Link](id + " " + name);
[Link]([Link]());
}
}

XML Configuration [1] :


<bean id="a1" class="[Link]">
<constructor-arg value="ghaziabad"></constructor-arg>
<constructor-arg value="UP"></constructor-arg>
<constructor-arg value="India"></constructor-arg>
</bean>
<bean id="e" class="[Link]">
<constructor-arg value="12" type="int"></constructor-arg>
<constructor-arg value="Sonoo"></constructor-arg>
<constructor-arg><ref bean="a1"/></constructor-arg>
</bean>

Setter Injection: Useful for optional dependencies; injects via setter methods [1] .
Example:
@Service
public class ProductService {
private ProductRepository productRepository;
@Autowired
public void setProductRepository(ProductRepository productRepository)
[Link] = productRepository;
}
}

Benefits of DI/IoC:
Loose Coupling: Reduces dependencies between classes [1] [2] .
Reusability: Components can be reused in different contexts [1] .
Testability: Easier to test with mock dependencies [1] [2] .
Configuration Management: Spring container manages lifecycle and configuration [1] .

Spring Container
Definition: Core component (heart) of Spring Framework, responsible for managing beans
and their lifecycle [1] .
Responsibilities:
Bean Management: Creation, initialization, and destruction of objects [1] .
Dependency Injection: Injects dependencies between objects [1] .
AOP Support: Facilitates aspect-oriented programming [1] .

Transaction Support: Manages transactions [1] .


Internationalization: Supports multiple languages [1] .
Integration: Connects with other frameworks [1] .
Types of Containers:
BeanFactory: Legacy container with basic IoC functionality [1] .

ApplicationContext: Modern, interface-based container with enhanced features;


currently used to invoke Spring container [1] .

Beans in Spring
Definition: Objects managed by the Spring IoC container, forming the backbone of the
application [2] .
Bean Scopes: Define the lifecycle and instance creation of beans [1] [2] .
Singleton (Default): One instance per Spring IoC container; shared across the
application [1] [2] .
Example: A website logo shared across all pages [2] .
Prototype: New instance created each time a request is made; suitable for stateful
beans [2] .
Example: A vending machine creating a new sandwich per request [2] .

Request: New instance per HTTP request; scoped to individual request [2] .

Example: A shopping cart specific to a user’s current request [2] .

Session: One instance per HTTP session; persists for session duration [2] .
Example: User preferences during a website session [2] .
Application: One instance per ServletContext; shared across the web application [2] .
Example: Trending articles visible to all users on a website [2] .

WebSocket: Scoped to WebSocket session lifecycle; used for real-time communication


[2] .
Autowiring in Spring
Definition: Automatically resolves and injects dependencies into beans, reducing explicit
configuration [1] [2] .
Enabling Autowiring: Use @Autowired annotation for constructor, setter, or field injection [1]
[2] .

Example [2] :

@Component
class InventoryService {
public void checkInventory(String item) {
[Link]("Checking inventory for item: " + item);
}
}
@Component
class OrderService {
private final InventoryService inventoryService;
@Autowired
public OrderService(InventoryService inventoryService) {
[Link] = inventoryService;
}
public void placeOrder(String item) {
[Link](item);
[Link]("Order placed for item: " + item);
}
}

Autowiring Modes:
No: Default mode; no autowiring performed [1] [2] .

byName: Matches bean by name; uses setter injection [1] [2] .


byType: Matches bean by type [1] [2] .

Constructor: Injects via constructor [1] [2] .


Autodetect: Combines constructor and byType modes [1] [2] .
Example (byName Mode) [1] :

<bean id="b" class="[Link].B"></bean>


<bean id="a" class="[Link].A" autowire="byName"></bean>

Advantages: Reduces code by avoiding explicit dependency injection [1] .


Disadvantages: Less control for programmers; not usable for primitive or String values [1] .

Aspect-Oriented Programming (AOP)


Definition: Complements OOP by modularizing cross-cutting concerns (e.g., logging,
security) using aspects instead of classes [1] [2] .
Cross-Cutting Concerns: Issues affecting the entire application, such as transaction
management, authentication, and logging [1] .
Key Terminologies [1] :

Aspect: Module for cross-cutting concerns (e.g., logging module).


Join Point: Point where aspect code is applied (e.g., method execution).
Advice: Actual code implementation; types include Before, After, After Returning, After
Throwing, and Around.
Pointcut: Set of join points where advice is executed.
Introduction: Adding new methods/attributes to existing classes.
Target Object: Object advised by aspects.
Weaving: Linking aspects with application objects at compile-time, runtime, or load-
time.
Example (Annotation-Based AOP):
@Aspect
public class LoggingAspect {
@Before("execution(* [Link].*.*(..))")
public void logBeforeMethod() {
[Link]("Logging before method execution");
}
}

Annotations in Spring
Purpose: Provide metadata for declarative configuration, reducing XML usage.
Core Annotations:
@Configuration: Marks class as source of bean definitions.
@Bean: Defines a bean programmatically.
@Component: Marks class as a Spring bean for component scanning.
@Autowired: Enables automatic dependency injection.
@Service, @Repository, @Controller: Specialized @Component for specific layers.
Spring Boot and MVC Annotations:
@SpringBootApplication: Combines auto-configuration and component scanning.
@RequestMapping, @GetMapping, @PostMapping: Maps HTTP requests to methods.

Lifecycle Callbacks
Purpose: Hook into bean lifecycle for custom initialization and destruction.
Mechanisms:
Interfaces: InitializingBean (afterPropertiesSet()) and DisposableBean (destroy()).
Annotations: @PostConstruct (after initialization) and @PreDestroy (before destruction).
Custom Methods: Define init-method and destroy-method in XML or @Bean.
Execution Order: @PostConstruct before custom init; @PreDestroy before custom destroy.
Example:
public class ExampleBean {
@PostConstruct
public void init() {
[Link]("Bean is initialized");
}
@PreDestroy
public void cleanup() {
[Link]("Bean is about to be destroyed");
}
}

Bean Configuration Styles


XML-Based: Traditional, verbose; uses <bean> tags for definitions.
Example:
<bean id="exampleBean" class="[Link]">
<property name="message" value="Hello World!"/>
</bean>

Annotation-Based: Uses annotations like @Component and @Autowired in code.


Java-Based: Uses @Configuration and @Bean for programmatic configuration.
Example:
@Configuration
public class AppConfig {
@Bean
public ExampleBean exampleBean() {
return new ExampleBean();
}
}

Groovy-Based: Uses Groovy scripts (less common).


Mixed: Combines XML, annotations, and Java configurations.

Spring Boot Specifics

Build Systems
Maven: Uses [Link] for dependencies and build; inherits spring-boot-starter-parent.
Gradle: Uses [Link]; supports concise syntax with Spring Boot plugins.
Both integrate with Spring Initializr for project setup.
Code Structure
Standard Layout:
src/main/java: Java source code (e.g., [Link] with @SpringBootApplication).
Packages: controller/, service/, repository/, model/.
src/main/resources: Configuration ([Link]), templates, static files.
src/test/java: Tests with @SpringBootTest.

Spring Boot Runners


Main Runner: [Link]() in @SpringBootApplication class.
CommandLineRunner/ApplicationRunner: Execute custom code post-context
initialization.
Example:
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
[Link]("Inspecting beans...");
};
}

Logging in Spring Boot


Framework: Uses SLF4J with Logback by default.
Configuration: Set levels in [Link] (e.g., [Link]=INFO).
Usage:
private static final Logger logger = [Link]([Link]);
[Link]("Processing request...");

Building RESTful Web Services


Key Annotations:
@RestController: Handles REST requests, returns data (e.g., JSON).
@RequestMapping: Maps HTTP requests; shorthand includes @GetMapping, @PostMapping.
@RequestBody: Binds request body to parameter (e.g., JSON).
@PathVariable: Extracts URI path values.
@RequestParam: Extracts query parameters.
HTTP Methods for CRUD:
GET: Retrieve data (@GetMapping).
POST: Create resources (@PostMapping).
PUT: Update resources (@PutMapping).
DELETE: Remove resources (@DeleteMapping).
Example (GET):
@GetMapping("/api/users/{id}")
public String getUser(@PathVariable Long id) {
return "User ID: " + id;
}

Building Web Applications


Setup: Use spring-boot-starter-web for MVC and embedded Tomcat.
MVC Pattern: Model (entities), View (templates like Thymeleaf), Controller (@Controller).
Static Resources: Served from src/main/resources/static.

Key Points for Exam Focus


Understand IoC and DI with examples of tight vs. loose coupling.
Memorize bean scopes (Singleton, Prototype, Request, Session, Application, WebSocket)
with real-world analogies.
Know autowiring modes and their implications.
Grasp AOP concepts and terminologies for cross-cutting concerns.
Familiarize with Spring Boot annotations for REST APIs and web development.
Review lifecycle callbacks and configuration styles for bean management.
These notes provide a comprehensive, structured overview of Spring Framework and Spring
Boot, combining theoretical concepts, practical examples, and key annotations to aid in exam
preparation. Focus on code snippets and examples to reinforce understanding of dependency
injection and RESTful service creation.

1. [Link]
2. [Link]

You might also like