OOPs Unit 5 Notes
OOPs Unit 5 Notes
Unit: - 5
Spring framework & Spring Boot
Spring framework
Features:
1. Lightweight
2. Dependency Injection (DI)
3. Aspect-Oriented Programming (AOP)
4. Transaction Management
5. MVC Framework
@Component
class Car {
private Engine engine;
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
}
2. Setter Injection
@Component
class Car {
private Engine engine;
@Autowired
public void setEngine(Engine engine) {
this.engine = engine;
}
}
3. Field Injection
@Component
class Car {
@Autowired
private Engine engine;
}
o Configuring them
o Wiring dependencies
Pointcut An expression that selects one or more join points All methods in a package
2. Prototype
Description: A new instance is created each time the
bean is requested from the container.
Use Case: When you need a fresh instance for each
request.
Defined As:
@Scope("prototype")
Behaviour:
o Created on demand.
o Spring does not manage the complete lifecycle after
instantiation.
3. Request (Web-aware scope)
Description: One instance per HTTP request. Valid only
in web-aware applications.
Use Case: When a bean should serve one HTTP request.
Defined As:
@Scope("request")
Behaviour:
o A new bean instance is created for each request
and discarded afterward.
4. Session
Description: One instance per HTTP session.
Use Case: For user session-based data.
Defined As:
@Scope("session")
Behaviour:
o Bean is tied to the lifecycle of the user’s session.
5. Application
Description: One instance per ServletContext.
Use Case: When a bean is needed across the entire web
application.
Defined As:
@Scope("application")
Behaviour:
o Shared across all sessions and requests in a web
app.
6. WebSocket
Description: One instance per WebSocket session.
Use Case: For stateful WebSocket communications.
Defined As:
@Scope("websocket")
Behaviour:
o Exists throughout a WebSocket session.
Auto-wiring in Spring
Why Autowiring?
Traditionally, beans were configured like this (manual
wiring):
<bean id="car" class="com.example.Car">
<property name="engine" ref="engine"/>
</bean>
With auto wiring, Spring can automatically match and
inject the engine bean into car without explicitly
defining the property.
Benefits of Autowiring
Reduces boilerplate XML/Java configuration.
Promotes loose coupling between components.
Simplifies unit testing and mocking.
Encourages dependency injection best practices.
Annotations in Spring
a) InitializingBean
Method: afterPropertiesSet()
Called after all properties are set by Spring.
@Component
public class MyBean implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception
{
System.out.println("Bean initialized
(afterPropertiesSet)");
}
}
b) DisposableBean
Method: destroy()
Called just before the bean is destroyed.
@Component
public class MyBean implements DisposableBean {
@Override
public void destroy() throws Exception {
System.out.println("Bean destroyed
(destroy)");
}
}
Different bean configuration styles in spring
2. Annotation-Based Configuration
Uses annotations like @Component, @Autowired, etc.,
directly in the Java code.
Requires component scanning to detect annotated
classes.
🔹 Example:
@Component
public class Engine {}
@Component
public class Car {
@Autowired
private Engine engine;
}
3. Java-Based Configuration (@Configuration +
@Bean)
Configuration is done using pure Java code instead of
XML.
Gives full control over bean creation logic.
🔹 Example:
@Configuration
public class AppConfig {
@Bean
public Engine engine() {
return new Engine();
}
@Bean
public Car car() {
return new Car(engine());
}
}
o @EnableAutoConfiguration
o @ComponentScan
3. Service Layer
Contains business logic of the application.
Annotated with @Service.
Called by controller classes.
Example:
@Service
public class UserService {
public List<User> getAllUsers() {
// Business logic
}
}
4. Repository Layer
Handles database operations.
Interfaces extend JpaRepository or CrudRepository.
Annotated with @Repository.
Example:
Repository
public interface UserRepository extends
JpaRepository<User, Long> {}
tables.
Annotated with @Entity, @Id, @GeneratedValue, etc.
Example:
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
}
RESTful Web Services in Spring Boot
Advantages:
1.Simplicity:
Annotations like @RestController make code much
simpler and clear.
2.Rapid Development:
Spring Boot handles configuration and boilerplate code,
allowing you to focus on business functionality.
3.Scalable:
Easily handle large amounts of requests with
lightweight, stateless services.
Platform-Independent:
Allows communication between different platforms
(Java, .NET, Python) over HTTP.
4.JSON Format:
By default, Spring converts Java Objects to JSON, which
is lightweight and widely supported.
5.Easy Integration:
Integrates smoothly with Spring components like
Security, Validation, and Data Access.
@RestController & @RequestMapping
That means:
All methods in the controller return the actual data (like
JSON or text) instead of view names.
Example:
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello(){
return "Hello from Spring Boot!";
}
}
Example:
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/users")
public List<String> getAllUsers(){
return List.of("Alice", "Bob", "Charlie");
}
}
1.GET API:
Purpose: Retrieve or read existing resources.
Spring Annotation: @GetMapping
Example:
@RestController
@RequestMapping("/students")
public class StudentController {
@GetMapping
public List<String> getAllStudents(){
return List.of("Alice", "Bob", "Charlie");
}
}
2.POST API:
Purpose: Create or add a new resource.
Spring Annotation: @PostMapping
@RequestBody: converts incoming JSON into Java
object.
Example:
@RestController
@RequestMapping("/students")
public class StudentController {
@PostMapping
public String addStudent(@RequestBody String
student){
// Here we would normally save student to
database
return "Student added: " + student;
}
}
PUT API:
Purpose: Update an existing resource.
Spring Annotation: @PutMapping
@PathVariable: specifies which resource to update.
Example:
@RestController
@RequestMapping("/students")
public class StudentController {
@PutMapping("/{id}")
public String updateStudent(@PathVariable int id,
@RequestBody String student){
// Update student with given id
return "Student " + id + " updated to " + student;
}
}
DELETE API:
Purpose: Remove or delete a resource.
Spring Annotation: @DeleteMapping
Example:
@RestController
@RequestMapping("/students")
public class StudentController {
@DeleteMapping("/{id}")
public String deleteStudent(@PathVariable int id){
// Delete student with given id
return "Student " + id + " removed.";
}
}