Notes/Advanced Programming/IoC and Spring.md
2024-12-07 21:07:38 +01:00

189 lines
4.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
type: practical
---
## IoC Definition
Inversion of Control is a design principle in which custom code is executed by an external code. The control of parts of your code is delegated to another logical unit.
>Think of when you submit assignment to Themis.
You did not write the tests in the program, but they still get executed against your program, as long as the input and output processing is correct.
## Dependency Injection
It is a technique where an object receives (or is "injected" with) other objects that it depends on, rather than creating those objects itself.
### Example
<u>CoffeeBean.java</u>
```java
public class CoffeeBean {
private String type;
public CoffeeBean(String type) {
this.type = type;
}
public String getType() {
return type;
}
}
```
<u>Water.java</u>
```java
public class Water {
private int amount;
public Water(int amount) {
this.amount = amount;
}
public int getAmount() {
return amount;
}
}
```
<u>CoffeeMachine.java</u>
```java
public class CoffeeMachine {
private CoffeeBean coffeeBean; // <--------
private Water water; // Dependencies
public CoffeeMachine(CoffeeBean coffeeBean, Water water) {
this.coffeeBean = coffeeBean;
this.water = water;
}
public void makeCoffee() {
if (coffeeBean == null || water == null) {
System.out.println("He-Hell nah.");
return;
}
System.out.println("Making coffee with " + coffeeBean.getType() + " beans and " + water.getAmount() + "ml of water.");
}
}
```
And then when we instantiate `CoffeeMachine`, we **pass instances** of `Water` and `coffeeBean`.
### How Does Spring Use DI?
Spring manages the **creation** and **wiring** of objects for you. Heres how it works:
1. **Beans**: Objects managed by Spring.
2. **Spring Container**: Factory which creates beans. You always need the container.
### `@Container` vs `@Bean` vs `@Component`
- A `Component` is a `Container` all of which's methods are `Beans`
- `Bean` is a Method managed by Spring
- `Container` is the class decorator which tells spring that we have beans inside
## Spring Basics
![Video](https://www.youtube.com/watch?v=LSEYdU8Dp9Y)
Spring is a **framework**, hence *its* design has to be followed.
### Quickstart
1. Import (mvn)
2. Add `@SpringBootApplication`, import and `SpringApplication.run(Main.class)`
#### Handling a REST client
Example:
```java
// Blah blah imports blah
@Controller
public class Control {
@GetMapping("/api/path_to_resource/{dynamicValue}") // <- GET
public String lmao(@PathVariable String value) {
return "You gave me " + value;
}
@PostMapping("/api/setLol") // <- POST
public String lmao(@RequestBody String value) {
System.out.println("Received: " + value);
}
// We can also parse json n stuff
@PostMapping("/api/yoMama")
public ResponseEntity<String> parseJson(@RequestBody yoMama obj) {
String response = "Received object: name = " + obj.getName() +
", number = " + obj.getNumber() +
", hot = " + obj.isHot();
System.out.println(response);
return ResponseEntity.ok(response);
}
}
}
class yoMama {
@Getter @Setter
private String name;
@Getter @Setter
private int number;
@Getter @Setter
private boolean hot;
public yoMama() {
}
}
```
## Beans
> beans can only be uses by beans
![[Beans.canvas|Beans]]
### Definition
- Any class that is a dependency and/or is dependent
### Purpose
- Solve the problem of dependencies by traversing the project's classes and instantiating them topologically in a procedural manner
### Annotations
Check out the [[Annotation Repository]].
## Components
### Entity
- Table in a DB
- Annotated with `@Entity`
- Instance corresponds to a row in the DB table
### DTO (Data Transfer Object)
- Java object used to transfer data b/n layers
- Decouple internal data from data exposed to client
- Contain only the necessary fields
### Repository
- Encapsulates storage, retrieval and search from a DB
- Usually extended from `CrudRepository` or `JpaRepository`
- Provides CRUD (Create, Read, Update and Delete) operations and query methods for an entity
### Controller
- Handles HTTP requests and returns responses
- Maps HTTP requests to specific methods
- Usually annotated with `@RestController` and `@RequestMapping`
### Service
- Class that contains logic and operations
- Intermediary between [Controller](IoC%20and%20Spring.md#Controller) and [Repository](IoC%20and%20Spring.md#Repository)
- Annotated with `@Service`