Spring & Spring Boot - AKTU BCS403H (Unit 5) Simplified Notes
Spring Core Basics
Spring is a powerful Java framework used to build enterprise-level applications. It helps write clean, loosely
coupled code by using concepts like Dependency Injection (DI) and Inversion of Control (IoC).
Dependency Injection (DI)
It means giving required objects to a class from outside. It allows flexibility and
better testing.
Types:
- Constructor Injection
- Setter Injection
Spring IoC (Inversion of Control)
IoC means Spring creates objects and manages their dependencies.
The 'container' (like ApplicationContext) handles object creation and wiring.
Aspect-Oriented Programming (AOP)
AOP separates cross-cutting concerns like logging or security.
Key Terms:
- Aspect: Common logic like logging
- Advice: When to run (before/after)
- Pointcut: Where to apply advice
- Join Point: Exact place in code
Bean Scopes
Defines lifespan of beans in Spring:
- singleton: One bean per container
- prototype: New bean on every request
- request/session/application/websocket: Used in web applications
Spring & Spring Boot - AKTU BCS403H (Unit 5) Simplified Notes
Autowiring
Spring automatically connects objects using @Autowired.
Example:
@Autowired
private UserService userService;
Annotations
Used to configure beans easily:
- @Component, @Service, @Repository
- @Autowired
- @PostConstruct, @PreDestroy
- @Configuration, @Bean
Bean Lifecycle Callbacks
You can run custom code after bean is created or before it's destroyed:
- @PostConstruct
- @PreDestroy
Bean Configuration Styles
1. XML-based (old)
2. Annotation-based (@Component)
3. Java Config-based using @Configuration + @Bean
Spring Boot Basics
Spring Boot simplifies Spring setup. No XML needed. It uses auto-configuration and embedded server.
Build Systems
Spring Boot uses Maven/Gradle to manage dependencies and build the project.
Spring Boot Code Structure
- src/main/java: Your Java code
Spring & Spring Boot - AKTU BCS403H (Unit 5) Simplified Notes
- src/main/resources: config files like application.properties
Spring Boot Runners
Run code at startup using:
- CommandLineRunner
- ApplicationRunner
Logger
Used to print info/errors in console.
Example:
private static final Logger logger = LoggerFactory.getLogger(MyClass.class);
logger.info("App started");
RESTful Web Services
Spring Boot makes it easy to build REST APIs using annotations like @RestController,
@GetMapping, etc.
REST Controller Example
A simple API example:
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
}
Annotations Used
Spring & Spring Boot - AKTU BCS403H (Unit 5) Simplified Notes
- @RequestBody: reads JSON input
- @PathVariable: gets value from URL
- @RequestParam: reads query params
Example:
@PostMapping("/add")
public String addUser(@RequestBody User user) { ... }
API Types
- GET: fetch data
- POST: add new data
- PUT: update existing data
- DELETE: remove data