Skip to content

Commit c7d8e55

Browse files
author
Nguyen Hoang Nam
committed
1 parent b37e367 commit c7d8e55

File tree

9 files changed

+398
-0
lines changed

9 files changed

+398
-0
lines changed

pom.xml

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
<module>spring-cloud-config-client</module>
2121
<module>spring-boot-helloworld-@Primary - @Qualifier</module>
2222
<module>spring-boot-3-bean-life-cycle-@PostConstruct-@PreDestroy</module>
23+
<module>spring-boot-4-@Component-@Service-@Repository</module>
2324
</modules>
2425
<parent>
2526
<groupId>org.springframework.boot</groupId>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<parent>
6+
<artifactId>spring-boot-learning</artifactId>
7+
<groupId>me.loda.spring</groupId>
8+
<version>0.0.1-SNAPSHOT</version>
9+
</parent>
10+
<modelVersion>4.0.0</modelVersion>
11+
12+
<artifactId>spring-boot-4-@Component-@Service-@Repository</artifactId>
13+
14+
<dependencies>
15+
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
16+
<dependency>
17+
<groupId>org.apache.commons</groupId>
18+
<artifactId>commons-lang3</artifactId>
19+
<version>3.9</version>
20+
</dependency>
21+
<dependency>
22+
<groupId>org.apache.commons</groupId>
23+
<artifactId>commons-lang3</artifactId>
24+
<version>3.9</version>
25+
</dependency>
26+
</dependencies>
27+
28+
</project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,271 @@
1+
# Source
2+
Vào link để xem chi tiết có hình ảnh minh họa:
3+
4+
[Loda.me - 「Spring Boot #4@Component vs @Service vs @Repository](https://loda.me/spring-boot-4-component-vs-service-vs-repository-loda1557627097246)
5+
# Content without images
6+
7+
### Giới thiệu
8+
9+
Trong bài trước chúng ta đã tìm hiểu các khái niệm căn bản và cần thiết trong Spring Boot.
10+
11+
1. [「Spring Boot #1」Hướng dẫn @Component và @Autowired][link-spring-boot-1]
12+
2. [「Spring Boot #2@Autowired - @Primary - @Qualifier][link-spring-boot-2]
13+
3. [「Spring Boot #3」Spring Bean Life Cycle + @PostConstruct và @PreDestroy][link-spring-boot-3]
14+
15+
Trong bài này tôi sẽ giới thiệu với các bạn các khái niệm về `@Component`, `@Service`, `@Repository`.
16+
17+
### Kiến trúc trong Spring Boot
18+
19+
Kiến trúc MVC trong Spring Boot được xây dựng dựa trên tư tưởng "độc lập" kết hợp với các nguyên lý thiết kế hướng đối tượng (một đại diện tiêu biểu là Dependency Inversion). Độc lập ở đây ám chỉ việc các layer phục vụ các mục đích nhất định, khi muốn thực hiện một công việc ngoài phạm vi thì sẽ đưa công việc xuống các layer thấp hơn.
20+
21+
Kiến trúc Controller-Service - Repository chia project thành 3 lớp:
22+
23+
![spring-bean-life-cycle](../../images/loda1557627097246/2.png)
24+
25+
**Consumer Layer hay Controller:** là tầng giao tiếp với bên ngoài và handler các request từ bên ngoài tới hệ thống.
26+
27+
**Service Layer:** Thực hiện các nghiệp vụ và xử lý logic
28+
29+
**Repository Layer:**: Chịu trách nhiệm giao tiếp với các DB, thiết bị lưu trữ, xử lý query và trả về các kiểu dữ liệu mà tầng Service yêu cầu.
30+
31+
### @Controller vs @Service vs @Repository
32+
33+
Để phục vụ cho kiến trúc ở trên, **Spring Boot** tạo ra 3 Annotation là `@Controller` vs `@Service` vs `@Repository` để chúng ta có thể đánh dấu các tầng với nhau.
34+
35+
Trong bài này, chúng ta sẽ tìm hiểu 2 Annotation `@Service` vs `@Repository` trước.
36+
37+
> `@Service` Đánh dấu một Class là tầng Service, phục vụ các logic nghiệp vụ.
38+
39+
> `@Repository` Đánh dấu một Class Là tầng Repository, phục vụ truy xuất dữ liệu.
40+
41+
### Cài đặt
42+
43+
_pom.xml_
44+
45+
```
46+
<?xml version="1.0" encoding="UTF-8"?>
47+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
48+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
49+
<modelVersion>4.0.0</modelVersion>
50+
<packaging>pom</packaging>
51+
<parent>
52+
<groupId>org.springframework.boot</groupId>
53+
<artifactId>spring-boot-starter-parent</artifactId>
54+
<version>2.0.5.RELEASE</version>
55+
<relativePath /> <!-- lookup parent from repository -->
56+
</parent>
57+
<groupId>me.loda.spring</groupId>
58+
<artifactId>spring-boot-learning</artifactId>
59+
<version>0.0.1-SNAPSHOT</version>
60+
<name>spring-boot-learning</name>
61+
<description>Everything about Spring Boot</description>
62+
63+
<properties>
64+
<java.version>1.8</java.version>
65+
</properties>
66+
67+
<dependencies>
68+
69+
<!--spring mvc, rest-->
70+
<dependency>
71+
<groupId>org.springframework.boot</groupId>
72+
<artifactId>spring-boot-starter-web</artifactId>
73+
</dependency>
74+
<dependency>
75+
<groupId>org.apache.commons</groupId>
76+
<artifactId>commons-lang3</artifactId>
77+
<version>3.9</version>
78+
</dependency>
79+
</dependencies>
80+
81+
<build>
82+
<plugins>
83+
<plugin>
84+
<groupId>org.springframework.boot</groupId>
85+
<artifactId>spring-boot-maven-plugin</artifactId>
86+
</plugin>
87+
</plugins>
88+
</build>
89+
90+
</project>
91+
```
92+
93+
Cấu trúc thư mục:
94+
95+
![spring-bean-life-cycle](../../images/loda1557627097246/3.png)
96+
97+
### Implement
98+
99+
Tôi tạo ra một model `Girl`.
100+
101+
```java
102+
public class Girl {
103+
private String name;
104+
105+
public Girl(String name) {
106+
this.name = name;
107+
}
108+
109+
public String getName() {
110+
return name;
111+
}
112+
113+
public void setName(String name) {
114+
this.name = name;
115+
}
116+
117+
@Override
118+
public String toString() {
119+
return "Girl(" + this.name + ")";
120+
}
121+
}
122+
123+
```
124+
125+
Tạo ra một interface `GirlRepository` để giao tiếp với DB.
126+
127+
```java
128+
public interface GirlRepository {
129+
/**
130+
* Tìm kiếm một cô gái trong database theo tên
131+
* @param name
132+
* @return
133+
*/
134+
Girl getGirlByName(String name);
135+
}
136+
```
137+
138+
Kế thừa `GirlRepository` và đánh dấu nó là `@Repository`
139+
140+
```java
141+
@Repository
142+
public class GirlRepositoryImpl implements GirlRepository {
143+
144+
@Override
145+
public Girl getGirlByName(String name) {
146+
// Ở đây tôi ví dụ là database đã trả về
147+
// một cô gái với tên đúng như tham số
148+
149+
// Còn thực tế phải query trong csđl nhé.
150+
return new Girl(name);
151+
}
152+
}
153+
```
154+
155+
Tạo ra một class `GỉrlService` để giải quyết các logic nghiệp vụ. Lớp `GirlService` sẽ giao tiếp với DB thông qua `GirlRepository`.
156+
157+
```java
158+
159+
import org.apache.commons.lang3.RandomStringUtils;
160+
import org.springframework.beans.factory.annotation.Autowired;
161+
import org.springframework.stereotype.Service;
162+
163+
@Service
164+
public class GirlService {
165+
@Autowired
166+
private GirlRepository girlRepository;
167+
168+
public Girl getRandomGirl(){
169+
// Random 1 cái tên độ dài 10
170+
String name = randomGirlName(10);
171+
172+
// Gọi xuông tầng repository để query lấy một cô gái tên là "name" trong database
173+
return girlRepository.getGirlByName(name);
174+
}
175+
176+
public String randomGirlName(int length) {
177+
// Random một string có độ dài quy định
178+
// Sử dụng thư viện Apache Common Lang
179+
return RandomStringUtils.randomAlphanumeric(length).toLowerCase();
180+
}
181+
}
182+
```
183+
184+
Chạy chương trình:
185+
186+
```java
187+
188+
import org.springframework.boot.SpringApplication;
189+
import org.springframework.boot.autoconfigure.SpringBootApplication;
190+
import org.springframework.context.ApplicationContext;
191+
192+
@SpringBootApplication
193+
public class App {
194+
195+
public static void main(String[] args) {
196+
ApplicationContext context = SpringApplication.run(App.class, args);
197+
198+
// Lấy ra bean GirlService
199+
GirlService girlService = context.getBean(GirlService.class);
200+
// Lấu ra random một cô gái từ tầng service
201+
Girl girl = girlService.getRandomGirl();
202+
// In ra màn hình
203+
System.out.println(girl);
204+
205+
}
206+
}
207+
208+
```
209+
210+
Output:
211+
212+
```
213+
Girl(ulmvchvgkf)
214+
```
215+
216+
### Giải thích
217+
218+
Về bản chất `@Service``@Repository` cũng chính là `@Component`. Nhưng đặt tên khác nhau để giúp chúng ta phân biệt các tầng với nhau.
219+
220+
Cùng nhìn vào source code của 2 Annotation này:
221+
222+
_Service.java_
223+
224+
```java
225+
@Target({ElementType.TYPE})
226+
@Retention(RetentionPolicy.RUNTIME)
227+
@Documented
228+
@Component // Cũng là một @Component
229+
public @interface Service {
230+
@AliasFor(
231+
annotation = Component.class
232+
)
233+
String value() default "";
234+
}
235+
236+
```
237+
238+
_Repository.java_
239+
240+
```java
241+
@Target({ElementType.TYPE})
242+
@Retention(RetentionPolicy.RUNTIME)
243+
@Documented
244+
@Component
245+
public @interface Repository {
246+
@AliasFor(
247+
annotation = Component.class
248+
)
249+
String value() default "";
250+
}
251+
252+
```
253+
254+
Trong các bài đầu tiên chúng ta đã biết `@Component` đánh dấu cho Spring Boot biết Class đó là `Bean`. Và hiển nhiên `@Service``@Repository` cũng vậy. Vì thế ở ví dụ trên chúng ta có thể lấy `GirlService` từ `ApplicationContext`.
255+
256+
Về bản chất thì bạn có thể sử dụng thay thế 3 Annotation `@Component`, `@Service``@Repository` cho nhau mà không ảnh hưởng gì tới code của bạn cả. Nó vẫn sẽ hoạt động.
257+
258+
Tuy nhiên từ góc độ thiết kế thì chúng ta cần phân rõ 3 Annotation này cho các Class đảm nhiệm đúng nhiệm vụ của nó.
259+
260+
- `@Service` gắn cho các `Bean` đảm nhiệm xử lý logic
261+
- `@Repository` gắn cho các `Bean` đảm nhiệm giao tiếp với DB
262+
- `@Component` gắn cho các `Bean` khác.
263+
264+
### Kết
265+
266+
Như mọi khi, [code được up tại Github][link-github]
267+
268+
[link-spring-boot-1]: https://loda.me/spring-boot-1-huong-dan-component-va-autowired-loda1557412317602
269+
[link-spring-boot-2]: https://loda.me/spring-boot-2-autowired-primary-qualifier-loda1557561089057
270+
[link-spring-boot-3]: https://loda.me/spring-boot-3-spring-bean-life-cycle-post-construct-va-pre-destroy-loda1557583753982
271+
[link-github]: https://github.com/loda-kun/spring-boot-learning
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package me.loda.spring.componentservicerepository;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
import org.springframework.context.ApplicationContext;
6+
7+
@SpringBootApplication
8+
public class App {
9+
10+
public static void main(String[] args) {
11+
ApplicationContext context = SpringApplication.run(App.class, args);
12+
13+
// Lấy ra bean GirlService
14+
GirlService girlService = context.getBean(GirlService.class);
15+
// Lấu ra random một cô gái từ tầng service
16+
Girl girl = girlService.getRandomGirl();
17+
// In ra màn hình
18+
System.out.println(girl);
19+
20+
}
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package me.loda.spring.componentservicerepository;
2+
3+
public class Girl {
4+
private String name;
5+
6+
public Girl(String name) {
7+
this.name = name;
8+
}
9+
10+
public String getName() {
11+
return name;
12+
}
13+
14+
public void setName(String name) {
15+
this.name = name;
16+
}
17+
18+
@Override
19+
public String toString() {
20+
return "Girl(" + this.name + ")";
21+
}
22+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package me.loda.spring.componentservicerepository;
2+
3+
public interface GirlRepository {
4+
/**
5+
* Tìm kiếm một cô gái trong database theo tên
6+
* @param name
7+
* @return
8+
*/
9+
Girl getGirlByName(String name);
10+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package me.loda.spring.componentservicerepository;
2+
3+
import org.springframework.stereotype.Repository;
4+
5+
@Repository
6+
public class GirlRepositoryImpl implements GirlRepository {
7+
8+
@Override
9+
public Girl getGirlByName(String name) {
10+
// Ở đây tôi ví dụ là database đã trả về
11+
// một cô gái với tên đúng như tham số
12+
// Để làm ví dụ.
13+
// Còn thực tế phải query trong csđl nhé.
14+
return new Girl(name);
15+
}
16+
}

0 commit comments

Comments
 (0)