0% found this document useful (0 votes)
22 views8 pages

Spring Boot

Spring Boot is an extension of the Spring Framework designed to simplify the development of production-ready applications through features like auto-configuration and starter dependencies. It provides a structured project setup, built-in support for REST APIs, and tools for monitoring and testing. Key annotations and configurations facilitate dependency injection, data persistence, and exception handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views8 pages

Spring Boot

Spring Boot is an extension of the Spring Framework designed to simplify the development of production-ready applications through features like auto-configuration and starter dependencies. It provides a structured project setup, built-in support for REST APIs, and tools for monitoring and testing. Key annotations and configurations facilitate dependency injection, data persistence, and exception handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 8

Spring Boot

What is Spring Boot?


Spring Boot is an extension of the Spring Framework that makes it easier and faster
to build production-ready applications.

It focuses on:

Convention over Configuration

Auto-Configuration

Standalone Applications

Key Features of Spring Boot


| Feature | Description |
| -------------------- | ------------------------------------------------- |
| Auto-configuration | Automatically configures beans based on classpath |
| Embedded servers | Comes with Tomcat, Jetty, or Undertow |
| Starter dependencies | Simplifies build configuration |
| Actuator | Provides production-ready monitoring endpoints |
| Spring Initializr | Quick project generation tool |
| DevTools | Enhances developer productivity with hot reload |

Architecture Overview
[ Client ] → [ Controller ] → [ Service ] → [ Repository ] → [ DB ]

Spring Boot (Auto Configuration, Dependency Injection, etc.)

1. Starter Dependencies
Spring Boot provides many pre-configured dependencies:

| Starter Name | Use |


| ------------------------------- | ------------------------------ |
| `spring-boot-starter-web` | For building web + REST apps |
| `spring-boot-starter-data-jpa` | For JPA + Hibernate ORM |
| `spring-boot-starter-security` | Spring Security integration |
| `spring-boot-starter-test` | Testing (JUnit, Mockito, etc.) |
| `spring-boot-starter-thymeleaf` | HTML templating engine |

2. Spring Boot Annotations

| Annotation | Purpose
|
| ----------------------------- |
-----------------------------------------------------------------------------------
---------- |
| `@SpringBootApplication` | Main entry point, includes `@Configuration`,
`@EnableAutoConfiguration`, and `@ComponentScan` |
| `@RestController` | REST controller (`@Controller + @ResponseBody`)
|
| `@GetMapping`, `@PostMapping` | Maps HTTP methods to controller methods
|
| `@Autowired` | Dependency Injection
|
| `@Service` | Marks a service class
|
| `@Repository` | Marks a DAO/repo class
|
| `@Entity` | Marks a JPA entity
|
| `@Component` | Marks any Spring-managed component
|

3. Spring Boot Project Structure

com.example.demo

├── controller
│ └── UserController.java
├── service
│ └── UserService.java
├── repository
│ └── UserRepository.java
├── model
│ └── User.java
├── DemoApplication.java <-- Main class
└── application.properties

4. Application Properties
Used to configure application-level settings.

Common Configurations:

server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=pass
spring.jpa.hibernate.ddl-auto=update

5. Spring Data JPA with Spring Boot


Repository interfaces auto-implement CRUD methods.

public interface UserRepository extends JpaRepository<User, Long> {


Optional<User> findByEmail(String email);
}

6. REST APIs

@RestController
@RequestMapping("/users")
public class UserController {

@Autowired
private UserService userService;
@GetMapping
public List<User> getAll() {
return userService.getUsers();
}

@PostMapping
public User save(@RequestBody User user) {
return userService.saveUser(user);
}
}

7. Spring Boot DevTools

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>

8. Spring Boot Actuator


Adds endpoints for monitoring and managing your app.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Example Endpoints:
/actuator/health

/actuator/info

/actuator/metrics

9. Exception Handling
Global Handler:

@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> handleNotFound(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}

10. Spring Security Integration (Optional)

Basic Setup:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

Configuration:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {

http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBa
sic();
}
}

11. Testing

@SpringBootTest
class UserServiceTest {
@Autowired
private UserService userService;

@Test
void testGetUsers() {
List<User> users = userService.getUsers();
assertNotNull(users);
}
}

Summary Table

| Feature | Description |
| ------------------------ | ----------------------------------- |
| `@SpringBootApplication` | Main config class |
| Starters | Predefined dependencies |
| Autoconfiguration | Reduces manual configuration |
| Embedded Server | No need for WAR file |
| REST Controller | Simple RESTful APIs |
| JPA Integration | Simple ORM with Spring Data JPA |
| DevTools | Auto-reload on changes |
| Actuator | Health, info, and metrics endpoints |

Spring & Spring Boot Annotations

1. Core Annotations

| Annotation | Purpose
|
| ------------------------ |
----------------------------------------------------------------------- |
| `@SpringBootApplication` | Combines `@Configuration`, `@EnableAutoConfiguration`,
`@ComponentScan` |
| `@Component` | Generic stereotype for any Spring-managed component
|
| `@Controller` | Marks a web controller (returns views)
|
| `@RestController` | `@Controller` + `@ResponseBody` (returns JSON/XML)
|
| `@Service` | Marks a service class (business logic layer)
|
| `@Repository` | Marks a DAO class; enables exception translation
|
| `@Configuration` | Marks a class with `@Bean` methods (Java-based config)
|

2. Dependency Injection

| Annotation | Description
|
| ------------------------ |
--------------------------------------------------------- |
| `@Autowired` | Auto-wires a bean by type (field, setter, or
constructor) |
| `@Qualifier("beanName")` | Specifies exact bean to inject when multiple types
exist |
| `@Inject` | JSR-330 equivalent of `@Autowired`
|
| `@Value("${key}")` | Injects property from `application.properties` or YAML
|
| `@Primary` | Marks the default bean when multiple candidates exist
|
| `@Lazy` | Bean will be initialized lazily (on first use)
|

3. REST & Web MVC

| Annotation | Description |
| ----------------- | -------------------------------------------------- |
| `@RequestMapping` | Maps HTTP requests to controller methods (general) |
| `@GetMapping` | Shortcut for `@RequestMapping(method = GET)` |
| `@PostMapping` | Shortcut for `POST` |
| `@PutMapping` | Shortcut for `PUT` |
| `@DeleteMapping` | Shortcut for `DELETE` |
| `@PatchMapping` | Shortcut for `PATCH` |
| `@RequestParam` | Extracts query param, e.g. `?name=xyz` |
| `@PathVariable` | Extracts value from URL path |
| `@RequestBody` | Maps HTTP body to Java object |
| `@ResponseBody` | Return value written directly as response body |
| `@ResponseStatus` | Set custom HTTP status code |

4. Bean Configuration
| Annotation | Description |
| ------------ | ------------------------------------------------ |
| `@Bean` | Registers a method return value as a Spring bean |
| `@DependsOn` | Specifies bean dependencies |
| `@Scope` | Defines bean scope (singleton, prototype, etc.) |
| `@Profile` | Activates bean only in a specific profile |
5. Spring Boot Features

| Annotation | Description
|
| -------------------------------- |
---------------------------------------------------------------------- |
| `@EnableAutoConfiguration` | Enables Spring Boot auto-config (included in
`@SpringBootApplication`) |
| `@ComponentScan` | Scans packages for components to auto-register
|
| `@EnableConfigurationProperties` | Binds external config to Java classes
|
| `@ConfigurationProperties` | Binds multiple properties from
`application.properties` or `YAML` |

6. JPA & Database

| Annotation | Purpose
|
| --------------------------------------------------------- |
----------------------------------------- |
| `@Entity` | Marks a JPA entity
(mapped to DB table) |
| `@Table(name = "")` | Specifies table name
|
| `@Id` | Marks the primary key
|
| `@GeneratedValue` | Specifies primary key
generation strategy |
| `@Column(name = "")` | Maps a field to a DB
column |
| `@OneToOne` / `@OneToMany` / `@ManyToOne` / `@ManyToMany` | Define relationships
|
| `@JoinColumn` | Specifies foreign key
column |
| `@Transient` | Field is not
persisted in DB |
| `@Enumerated` | Persist enums as
`String` or `Ordinal` |

7. Validation (Hibernate Validator / Jakarta)

| Annotation | Purpose |
| ------------------- | ------------------------------------ |
| `@NotNull` | Field must not be null |
| `@NotBlank` | Not null and trimmed length > 0 |
| `@Size(min=, max=)` | String/collection length constraints |
| `@Email` | Validates email format |
| `@Pattern` | Regex pattern validation |
| `@Min`, `@Max` | Numeric range constraints |
| `@Valid` | Triggers nested object validation |
8. AOP (Aspect-Oriented Programming)

| Annotation | Purpose |
| ----------------- | ------------------------------------------- |
| `@Aspect` | Declares a class as an aspect |
| `@Before` | Runs before method execution |
| `@After` | Runs after method execution |
| `@AfterReturning` | Runs if method returns successfully |
| `@Around` | Runs before and after method (full control) |
| `@Pointcut` | Defines reusable pointcut expressions |

9. Testing

| Annotation | Description |
| -------------------- | ------------------------------------- |
| `@SpringBootTest` | Loads full application context |
| `@DataJpaTest` | Test JPA repositories only |
| `@WebMvcTest` | Test controller layer (mock MVC) |
| `@MockBean` | Adds Mockito mock into Spring context |
| `@TestConfiguration` | Defines test-specific beans |

10. Exception Handling

| Annotation | Description |
| ------------------- | ------------------------------------ |
| `@ControllerAdvice` | Global exception handling class |
| `@ExceptionHandler` | Handles specific exceptions |
| `@ResponseStatus` | Sets HTTP status on custom exception |

11. Scheduling & Async

| Annotation | Purpose |
| ------------------- | ---------------------------------- |
| `@EnableScheduling` | Enables scheduled task execution |
| `@Scheduled` | Schedules method (cron, fixedRate) |
| `@EnableAsync` | Enables asynchronous method calls |
| `@Async` | Executes method asynchronously |

12. Transaction Management

| Annotation | Purpose |
| ------------------------------ | ------------------------------ |
| `@EnableTransactionManagement` | Enables @Transactional support |
| `@Transactional` | Wraps method in DB transaction |
| `@Rollback` | Reverts changes in tests |

Summary Table

| Category | Example Annotations |


| ----------------- | ---------------------------------------------------- |
| **Core** | `@Component`, `@Service`, `@Configuration` |
| **Web / REST** | `@RestController`, `@GetMapping`, `@RequestBody` |
| **Persistence** | `@Entity`, `@Id`, `@OneToMany`, `@Repository` |
| **DI** | `@Autowired`, `@Value`, `@Qualifier` |
| **Boot-specific** | `@SpringBootApplication`, `@ConfigurationProperties` |
| **AOP** | `@Aspect`, `@Around`, `@Pointcut` |
| **Validation** | `@NotNull`, `@Email`, `@Size`, `@Valid` |
| **Testing** | `@SpringBootTest`, `@MockBean` |
| **Scheduling** | `@Scheduled`, `@EnableScheduling` |
| **Transactions** | `@Transactional`, `@EnableTransactionManagement` |

You might also like