Spring) Spring Boot Concepts / Java 17
This post was migrated from Tistory. You can find the original here.
concept
IoC
Inversion of Control
1
2
3
public class A{
b = new B();
}
In code like the above, A creates b directly itself.
Inversion of control means that instead of directly creating or controlling other objects, you take an externally-managed object and use it.
1
2
3
4
(1)
public class A{
private B b;
}
As shown above, b isn’t created directly — it’s obtained from somewhere else.
DI
Dependency Injection
This is the mechanism used to implement IoC.
1
2
3
4
public class A{
@Autowired
B b;
}
The @Autowired annotation injects a bean from the Spring container.
Object injection and management are handled by the Spring container, and having the container manage objects — creation, destruction, etc. — gives that lifecycle management consistency.
Structure
Basically, apps are organized into controller, service, and repository layers.
In order, these are also called the presentation layer, business layer, and persistence layer.
When you start with a Spring Boot starter, it seems that Tomcat handles request processing by default.
Request-response flow
AGET /testrequest -> the dispatcher servlet parses the URL and matches a controller -> it passes through the business and persistence layers to fetch the needed data -> the view resolver uses a template engine to generate HTML, JSON, XML, or other data -> the response is returned
For now, just keep in mind that the flow up to the response involves the dispatcher servlet and the view resolver.
java17
Spring Boot 2 uses Java 8 or higher,
while Spring Boot 3 uses Java 17 or higher.
Text blocks
Java 17 supports text blocks like the following.
1
2
3
4
5
6
7
String query = "SELECT * FROM \"items\"\n" +
"WHERE \"status\" = \"ON_SALE\"\n";
String query17 = """
SELECT * FROM "items"
WHERE "status" = "ON_SALE"
""";
It also provides formatted() for parsing.
1
2
3
4
5
6
String text17 = """
{
"id" : %d,
"name" : %s,
}
""".formatted(1, "choi");
Records
1
2
3
4
5
record Item(String name, int price) {
// parameters are automatically defined as private final
}
Item a = new Item("car", 1000);
a.price(); // auto-generated getter
Records cannot be extended, and the fields defined as parameters are automatically private final.
Also, since a getter is generated automatically, you don’t need to define getters yourself via annotations or methods.
Pattern matching
1
2
3
4
5
6
if (o instanceof Integer){
Integer i = (integer) o;
}
if (o instanceof Integer){
// in version 17, the cast happens automatically
}
The type cast now happens automatically.
Type-specific case handling
On my IntelliJ set to Java 17, this throws an error (passing on it for now).