Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

1.

Annotation trong JAVA và Spring Boot


- Annotation trong JAVA cung cấp thông tin bổ sung cho compiler và JVM. Nó biểu thị metadata cho các class, interface, variable, method, hoặc field.
- Spring Boot dựa vào annotation để đơn giản hóa quá trình configuration (cấu hình), define components (định nghĩa các component) và quản lý các khía cạnh khách
nhau của ứng dụng. Các annotation này là một phần của Spring ecosystem rộng hơn, rất nhiều trong số chúng có nguồn gốc từ Spring Framework, Spring MVC và
sau đó được điều chỉnh và mở rộng để sử dụng trong Spring Boot.

2. Các annotation chính được sử dụng trong Spring Boot

STT Annotation Giải thích Cách sử dụng


1 @SpringBootApplication Lập trình viên khi phát triển Spring Boot // Same as @SpringBootConfiguration
application thường muốn ứng dụng của họ sử dụng @EnableAutoConfiguration @ComponentScan
auto-configuration (cấu hình tự động), component @SpringBootApplication
scan (tự quét component) và có thể định nghĩa các public class MyApplication {
configuration bổ sung trên “application class”. Một
@SpringBootApplication annotation duy nhất có public static void main(String[] args) {
thể được sử dụng để sử dụng 3 chức năng đó, đó là: SpringApplication.run(MyApplication.class, args);
}
- @EnableAutoConfiguration: kích hoạt cơ chế
cấu hình tự động của Spring Boot }

- @ComponentScan: kích hoạt quét @Component Lưu ý: Không có tính năng nào trong số này là bắt buộc và bạn có thể chọn
trên package chứa application. thay thế một annotation này bằng bất kỳ tính năng nào mà nó kích hoạt. Ví
dụ: bạn có thể không muốn sử dụng component scan hoặc configuration
- @SpringBootConfiguration : cho phép đăng ký properties scan trong ứng dụng của mình:
các extra beans trong context hoặc import các
configuration classes bổ sung. Một giải pháp thay @SpringBootConfiguration(proxyBeanMethods = false)
@EnableAutoConfiguration
thế cho @Configuration tiêu chuẩn của Spring giúp
@Import({ SomeConfiguration.class,
hỗ trợ configuration detection trong các integration AnotherConfiguration.class })
tests. public class MyApplication {

public static void main(String[] args) {


SpringApplication.run(MyApplication.class, args);
}

Trong ví dụ này, MyApplication giống như bất kỳ ứng dụng Spring Boot
nào khác, ngoại trừ các lớp được chú thích bằng @Component và các lớp
được chú thích bằng @ConfigurationProperties không được phát hiện tự
động và các bean do người dùng định nghĩa được nhập rõ ràng (xem
@Import).
2 @Bean @Bean là một annotation cốt lõi trong Spring @Configuration
Framework được dùng để khai báo rằng một public class AppConfig {
method là một producer của một Spring bean. Khi
một method được annotate với @Bean, nó nói với @Bean
Spring IoC (Inversion of Control) container rằng public MyBean myBean() {
method sẽ trả về một đối tượng mà nên được quản return new MyBean();
lý như một bean. Container có trách nhiệm tạo, cấu }
hình, và quản lý vòng đời của bean. }

- @Configuration cho biết rằng lớp chứa các định nghĩa bean (Tất cả các
Method sử dụng annotation @Bean phải nằm trong class Configuration).
- Method myBean() được annotate bằng @Bean, cho biết nó tạo ra một bean
có tên là “myBean”.
- Method trả về một instance của MyBean, sẽ được quản lý bởi Spring IoC
container.
3 @Component @Component cũng được coi là một trong những @Component
Annotation được sử dụng nhiều nhất trong Spring public class MyComponent {
Boot. Đó là một class-level annotation, biến lớp đó // Class implementation
thành Spring Bean tại thời điểm tự động quét. Nó }
cho phép framework có thể autoditect những lớp
này để dependency injection. - @Component được sử dụng để annotate lớp MyComponent là một Spring
Lưu ý: component.
- Sẽ không thể @Autowire một lớp nếu lớp đó - Khi Spring IoC container quét classpath để tìm các component (như là một
không sử dụng @Component. phần của component scanning), nó phát hiện các lớp được annotate bằng
- Khi bạn muốn xác định lớp để Injection thì phải @Component và đăng ký chúng như các bean.
đánh dấu bằng cách sử dụng annotation này để
spring biết.

Các Stereotype Annotation bổ sung:


@Component là một dạng chuyên biệt của
stereotype annotation @Component chung hơn. Có
những stereotype annotation khác trong framework
Spring là các phần mở rộng của @Component và
phục vụ cho các mục đích cụ thể: @Service,
@Repository, @Controller,
@RestController…
4 @Entity @Entity annotation trong JPA (Java Persistence @Entity Annotation:
API) được sử dụng để đánh dấu một lớp Java là một @Entity
persistent entity. Một entity đại diện cho một bảng public class User {
trong relational database. Bên cạnh @Entity, có một @Id
số annotation liên quan trong JPA cung cấp thông @GeneratedValue(strategy = GenerationType.IDENTITY)
tin bổ sung và tùy chọn cấu hình. private Long id;

private String firstName;


private String lastName;
private String email;

// Getters and setters


}

- The class represents a table in the database, and each instance of the class
corresponds to a row in that table.
- @Id denotes the primary key field of the entity.
- @GeneratedValue specifies the generation strategy for the primary key
values.

@Table Annotation:
@Entity
@Table(name = "users")
public class User {
// Class details
}

- name attribute specifies the name of the table in the database.

@GeneratedValue Annotation:
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

- GenerationType.IDENTITY indicates that the database should


automatically generate the primary key values.

@Column Annotation:
@Column(name = "first_name", nullable = false, length =
50)
private String firstName;

@OneToMany and @ManyToOne Annotations:


@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

// Other fields

@OneToMany(mappedBy = "user")
private List<Order> orders;

// Getters and setters


}

@Entity
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

// Other fields

@ManyToOne
@JoinColumn(name = "user_id")
private User user;

// Getters and setters


}

- @OneToMany and @ManyToOne are used to define a one-to-many


relationship between two entities.
- @OneToMany(mappedBy = "user") specifies the inverse side of the
relationship in the User entity.
- @ManyToOne in the Order entity defines the owning side of the
relationship.
- @JoinColumn specifies the foreign key column in the Order table.

5 @Repository Là thành phần chính trong data access layer, chú @Repository
thích một lớp là một Spring Data repository. Nó public class UserRepository {
được sử dụng để chỉ ra rằng lớp có trách nhiệm bao // Data access methods
gồm việc lưu trữ, truy xuất và tìm kiếm liên quan }
đến các entity.
- The class is typically responsible for CRUD (Create, Read, Update, Delete)
operations on a specific entity (e.g., User).

import org.springframework.data.jpa.repository.JpaRepository;
Tích hợp Spring Data JPA: @Repository
@Repository thường được sử dụng kết hợp với public interface UserRepository extends JpaRepository<User,
Spring Data JPA để tạo các repository cho các thực Long> {
thể JPA. Spring Data JPA cung cấp một bộ tính // Custom query methods can be defined here
năng mạnh mẽ và tiện lợi để làm việc với các cơ sở }
dữ liệu quan hệ, bao gồm việc tạo tự động truy vấn
dựa trên tên phương thức và hỗ trợ phân trang. - UserRepository extends JpaRepository, which is a Spring Data JPA
interface providing CRUD operations for the User entity
- By extending JpaRepository, the UserRepository inherits various data access
methods, such as save, findById, findAll, delete, etc.

@Repository
public interface UserRepository extends
JpaRepository<User, Long> {
Các tính năng bổ sung: List<User> findByLastName(String lastName);
1. Custom Queries: You can define custom query }
methods in the repository interface, and Spring Data
JPA will automatically generate the corresponding @Repository
queries based on the method names. public interface UserRepository extends
JpaRepository<User, Long> {
2. Query Annotations: or more complex queries, @Query("SELECT u FROM User u WHERE u.age > :age")
you can use the @Query annotation to specify a List<User> findByAgeGreaterThan(@Param("age") int
JPQL (Java Persistence Query Language) or native age);
SQL query. }

3. Transactional Behavior: By default, methods in


a Spring Data repository are transactional. This
means that each method is wrapped in a transaction,
and changes to the data are committed or rolled
back as a single unit of work
6 @Service Chú thích một lớp là một service component trong Basic Usage:
service layer. Service components trong Spring @Service
thường được sử dụng để encapsulate business logic, public class UserService {
định nghĩa service operations, và hoạt động như một // Business logic and service operations
layer trung gian giữa controllers (trong web }
application) hoặc các components khác và data
access layer. Spring MVC Integration:
@Service
public class UserService {

@Autowired
private UserRepository userRepository;

public List<User> getAllUsers() {


return userRepository.findAll();
}

public User getUserById(Long userId) {


return
userRepository.findById(userId).orElse(null);
}

public void createUser(User user) {


userRepository.save(user);
}

public void updateUser(User user) {


userRepository.save(user);
}

public void deleteUser(Long userId) {


userRepository.deleteById(userId);
}
}

- The UserService class contains methods for performing CRUD operations


on users.
- It collaborates with a UserRepository for data access
7 @Controller @Controller annotation là một Spring stereotype Basic Usage:
annotation được sử dụng để dánh dấu một class là @Controller
Spring MVC (Model-View-Controller) controller. public class MyController {
Controllers trong Spring tiếp nhận các incoming
HTTP requests, xử lý chúng bằng cách gọi business @GetMapping("/hello")
logic phù hợp, và tạo ra một HTTP response. public String sayHello() {
return "hello";
}
}

Request Mapping: Request Mapping:


Controllers sử dụng các annotations khác nhau cho @Controller
request mapping, chỉ định method nào sẽ xử lý các @RequestMapping("/api/users")
URL hoặc HTTP methods cụ thể. Một số public class UserController {
annotations phổ biến bao gồm:
- @RequestMapping: Một annotation tổng quát có @GetMapping("/all")
thể được sử dụng cho các HTTP methods khác public String getAllUsers() {
nhau. // Logic to retrieve and display all users
- @GetMapping: Xử lý các yêu cầu HTTP GET. return "users";
- @PostMapping: Xử lý các yêu cầu HTTP POST. }
- @PutMapping: Xử lý các yêu cầu HTTP PUT.
- @DeleteMapping: Xử lý các yêu cầu HTTP @GetMapping("/details/{userId}")
public String getUserDetails(@PathVariable Long userId)
DELETE.
{
// Logic to retrieve and display user details
return "userDetails";
}
}

View Resolution:
View Resolution: @Controller
Controller methods thường trả về tên của một view public class MyController {
hoặc một ModelAndView object. Tên của view
được resolve (giải quyết) thành một view template @GetMapping("/hello")
thực tế bằng một view resolver configured trong public String sayHello(Model model) {
Spring application context. model.addAttribute("message", "Hello, Spring
MVC!");
return "helloPage";
}
}
8 @RestController @RestController là một phiên bản chuyên biệt của Basic Usage:
@Controller trong Spring framework. Nó được @RestController
thiết kế đặc biệt cho việc xây dựng RESTful web @RequestMapping("/api")
services, trong đó response thường có dạng dữ liệu public class ApiController {
(thông thường là JSON hoặc XML) thay vì một
trang HTML hoàn chỉnh. @RestController kết hợp @GetMapping("/greet")
public String greet() {
@Controller và @ResponseBody, loại bỏ nhu cầu
return "Hello, RESTful World!";
chú thích mỗi phương thức với @ResponseBody. }
}

- The @RequestMapping annotation at the class level sets the base URL for
all methods in the controller.
- The @GetMapping annotation specifies that the greet method should
handle HTTP GET requests for the "/api/greet" URL.

Request Mapping và HTTP Methods: Request Mapping và HTTP Methods:


@RestController sử dụng các request mapping @RestController
annotations tương tự như @Controller. Nó bao gồm @RequestMapping("/api/users")
các annotation như @GetMapping, @PostMapping, public class UserController {
@PutMapping, và @DeleteMapping để xử lý các
HTTP methods cụ thể. @GetMapping("/all")
public List<User> getAllUsers() {
// Logic to retrieve and return all users
}

@GetMapping("/details/{userId}")
public User getUserDetails(@PathVariable Long userId) {
// Logic to retrieve and return user details
}

@PostMapping("/create")
public ResponseEntity<String> createUser(@RequestBody User
user) {
// Logic to create a new user
return ResponseEntity.ok("User created
successfully");
}

@PutMapping("/update/{userId}")
public ResponseEntity<String> updateUser(@PathVariable
Long userId, @RequestBody User user) {
// Logic to update user information
return ResponseEntity.ok("User updated
successfully");
}

@DeleteMapping("/delete/{userId}")
public ResponseEntity<String> deleteUser(@PathVariable
Long userId){
// Logic to delete user
return ResponseEntity.ok("User deleted
successfully");
}
}

- @RequestBody annotation được sử dụng để gán request body vào tham số


của method.
Automatic Serialization:
Các phương thức trong một lớp @RestController tự Automatic Serialization:
động serialize (tuần tự hóa) giá trị trả về vào @RestController
response body. Mặc định, Spring sử dụng Jackson @RequestMapping("/api")
hoặc một configured message converter khác để public class ApiController {
chuyển đổi các object thành JSON (hoặc XML).
@GetMapping("/user")
public User getUser() {
User user = new User("John", "Doe",
"john.doe@example.com");
return user;
}
}

- Method getUser trả về User object, và được tự động serialized thành JSON
ResponseEntity và Status Codes: trong response body.
Các phương thức của @RestController thường trả
về một ResponseEntity để cung cấp nhiều kiểm soát ResponseEntity và Status Codes:
hơn đối với phản hồi HTTP, bao gồm các status @RestController
codes và các headers @RequestMapping("/api")
public class ApiController {

@GetMapping("/status")
public ResponseEntity<String> getStatus() {
return
ResponseEntity.status(HttpStatus.OK).body("Service is
running");
}
}
9 @Autowired @Autowired annotation trong Spring được dử dụng Constructor Injection:
để tự động inject dependencies vào trong Spring- @Service
managed beans. Nó có thể được áp dụng cho public class MyService {
fields/properties, setter methods, và constructors.
Khi Spring bắt gặp một bean với @Autowired private final MyRepository myRepository;
annotation, nó giải quyết và injects dependency phù
@Autowired
hợp, nhằm đạt được loose coupling và làm cho việc
public MyService(MyRepository myRepository) {
quản lý và test components dễ dàng hơn. this.myRepository = myRepository;
}

// Methods using myRepository


}

- Constructor injection is a preferred approach in modern Spring


applications.
- The @Autowired annotation can be placed on the constructor, and Spring
automatically injects the required dependencies when creating the
MyService bean.
Setter Injection:
@Component
public class MyService {

private MyRepository myRepository;

@Autowired
public void setMyRepository(MyRepository myRepository) {
this.myRepository = myRepository;
}

// Methods using myRepository


}

Field/Properties Injection:
@Component
public class MyService {

@Autowired
private MyRepository myRepository;

// Methods using myRepository


}

@Autowired và Optional Dependencies: Optional Dependency


Khi một bean đang được constructed, @Autowired @Service
dependencies phải có sẵn. Ngược lại, nếu Spring public class MyService {
không thể giải quyết (tìm được) bean để wiring, thì
nó sẽ throw an exception. @Autowired(required = false)
Để khắc phục điều này, chúng ta cần khai báo một private Optional<MyRepository> myRepository;
bean thuộc required type.
// Methods using myRepository (check for presence before
usage)
}

Autowire Disambiguation:
Autowiring by @Qualifier
Theo mặc định, Spring giải quyết @Autowired @Service
entries theo type. Nếu có nhiều hơn một bean cùng public class MyService {
loại available trong container, thì framework sẽ
throw a fatal exception. @Autowired
Một trong những giải pháp cho vấn đề này là @Qualifier("myJpaRepository")
Autowiring by @Qualifier private MyRepository myRepository;

// Methods using myRepository


}

- You can use the @Qualifier annotation to specify which bean to inject
10 @Value @Value trong Spring được sử dụng để inject giá trị Injecting Properties from Application Properties:
vào các bean được quản lý bởi Spring từ các nguồn # application.properties
bên ngoài, chẳng hạn như các property files, my.property=Hello, Spring!
environment variables hoặc các system properties.
Nó đặc biệt hữu ích để inject các giá trị đơn giản,
chẳng hạn như chuỗi hoặc số, vào các bean trong @Component
public class MyComponent {
quá trình khởi tạo.
@Value("${my.property}")
private String myProperty;

// Methods using myProperty


}

11 @Valid @Valid trong Spring được sử dụng kết hợp với Basic Usage in a Controller Method:
@RequestBody để chỉ ra rằng tham số phương thức @RestController
(thường là một Java bean đại diện cho một biểu mẫu @RequestMapping("/api/users")
hoặc một request payload) nên được validate trước public class UserController {
khi xử lý yêu cầu. Nó thường được sử dụng trong
các Spring MVC controllers để thực hiện validation @PostMapping("/create")
public ResponseEntity<String> createUser(@Valid
trên dữ liệu đầu vào.
@RequestBody UserDTO userDTO) {
// Process the userDTO if validation passes
// ...
return ResponseEntity.ok("User created
successfully");
}
}

Validation on DTO Class:


public class UserDTO {

@NotBlank(message = "Username cannot be blank")


private String username;

@Email(message = "Invalid email format")


private String email;
@Size(min = 8, message = "Password must be at least 8
characters long")
private String password;

// Getters and setters


}

You might also like