Share & grow the worlds knowledge!
We want to connect the people who have knowledge to the people who need it, to bring together people with different perspectives so they can understand each other better, and to empower everyone to share their knowledge.
Spring: singleton có ý nghĩa gì và tại sao lại phải tạo singleton?
Em chào anh.
Em mới mua sách "Làm chủ các mẫu thiết kế kinh điển trong lập trình" của anh. Em thấy ngay phần đầu tiên anh có đề cập đến singleton. Em mới chuyển ngành sang làm dev có một câu hỏi mong anh có thế giải thích ạ.
Trong Spring Boot singleton được tạo ra nếu đánh dấu nó là 1 bean, vậy singleton có ý nghĩa gì và tại sao lại phải tạo singleton. Để hiểu cách nó tạo ra thì làm như thế nào được ạ?
Remain: 5
1 Answer
tvd12
Enlightened
tvd12
Enlightened
Hãy nói em có một lớp UserService thế này:
public class UserService { public User getUserById(long userId) { // trả về user theo id } }
Tiếp theo chúng ta sẽ có một lớp là UserController để xử lý yêu cầu lấy thông tin người dung, Nếu bây giờ không sử dụng singleton thì mã nguồn sẽ như sau:
public class UserController { @GetMapping("/users/{userId}") public User getUserById(@PathVariable long userId) { UserService service = new UserService(); return userService.getUserById(userId); } }
Trên thực tế trong một thời điểm
UserController có thể phải xử lý rất nhiều yêu cầu, vậy mỗi yêu cầu lại sinh ra một đối tượng UserService, điều này làm tăng bộ nhớ cần tạo, ngoài ra gây ra tình trạng cấp, giải phóng bộ nhớ liên tục sẽ làm tiêu tốn cả tài nguyên CPU nữa.Ngoài ra trên thực thế lớp
UserService có thể phụ thuộc vào các lớp khác như UserRepository, như vậy thì việc khởi tạo sẽ cực kỳ phức tạp. Như vậy cần thiết phải sử dụng singleton để khởi tạo duy nhất một đối tượng cho lớp UserService để tiết kiệm tài nguyên, đồng thời cũng dễ dàng hơn trong việc khởi tạo các lớp phụ thuộc lẫn nhau, giải phóng lập trình viên khỏi việc khởi tạo các đối tượng để xử lý.Spring sử dụng reflection để quét các lớp trong package được chỉ định, sau đó cũng khởi tạo và inject các đối tượng phụ thuộc sử dụng reflection. Để tìm hiểu sâu vào bên trong thì chỉ có đọc source code của spring-context thôi em ạ.
-
0
- Reply
bố sung thêm 1 ví dụ khác sử dụng Dependency Injection (DI). tránh việc khởi tạo quá nhiều instance và khi nó không được sử dụng hoặc không có tham chiến thì sẽ trở thành "rác" (garbage). Trình quản lý bộ nhớ tự động (garbage collector) của Java sẽ quản lý và thu gom các đối tượng rác này. Nếu có quá nhiều rác thì sẽ dẫn đến :
1.Tiêu tốn tài nguyên bộ nhớ: Mỗi instance sẽ tiêu tốn một lượng tài nguyên bộ nhớ. Nếu tạo quá nhiều instance mà không giải phóng chúng, ứng dụng có thể tiêu tốn nhiều bộ nhớ hơn cần thiết, dẫn đến hiện tượng tốn tài nguyên và giảm hiệu suất.2.Hiệu suất kém: Nếu tạo quá nhiều instance và không quản lý chúng, có thể dẫn đến hiệu suất kém do overhead khi sử dụng bộ nhớ, sự cạnh tranh về tài nguyên bộ nhớ và thời gian cần thiết để garbage collector làm việc.3.Lỗi OutOfMemoryError: Nếu ứng dụng tạo quá nhiều instance và không giải phóng bộ nhớ đúng cách, nó có thể gây ra lỗi OutOfMemoryError, làm ứng dụng bị crash.@Service public class UserService { public User getUserById(long userId) { // Trả về user theo id } } @Controller public class UserController { @Autowired private UserService userService; @GetMapping("/users/{userId}") public User getUserById(@PathVariable long userId) { return userService.getUserById(userId); } }
- Question(s) 1.1K
- Answer(s) 2.2K
- Best answer(s) 136
- User(s) 548
-
Lâm Tấn Lộc added an answer <ul class="markdown-list"><li class="markdown-list-item"> Đầ... 1768014969000 -
-
Related Questions
Recent Activities
-
Voted up question. January 9, 2023 at 2:54 pm
-
Voted up question. January 9, 2023 at 2:54 pm
-
Voted up question. January 9, 2023 at 2:54 pm
-
Voted up question. January 9, 2023 at 2:54 pm
-
Voted up question. January 9, 2023 at 2:54 pm
Top Members
Trending Tags
.net
.net core
.net oop
#formatdate
abstract class
access app
access token
ai
android
ansible
anti-flooding
apache poi
api
app
architecture
artificial intelligence
assembly
async
asyncawait
atomicboolean
authentication
backend
backend nestjs
background
bash script
batch
bean
big project
binding
bitcoin
blockchain
blog
boot-nodes
branch
btree
bucket4j
buffered
build
bundle
c#
c# .net
cache
caching
callback
career
career path
cast
câu hỏi
centos
chat
cloud
cloud reliability
combobox
commit
communication
computer science
concurrent
config-css
connection pool
content-disposition
contract
controllerservice
convert date to number
cookie
cors
cosmos
cosmos-sdk
crawl data
cron
css
database
database migration
datasource
datastructure
datetime
deadlock
debug
decentralized exchange
deep learning
deploy contract
design patterns
design-pattern
dev
devops
dex
di
distraction programing
dns
đồ án tốt nghiệp
docker
download
draw.io
du học
dữ liệu lớn
duration
eclip
editor
elasticsearch
email
erc20
erc721
error
estimation
eth
ethereum
ethereum login
excel
excel-object-mapper
exception
exception handle
exception handler
executor
export compliance
extensions
exyfox
ezydata
ezyfox
ezyfox-boot
ezyfox-server
ezyfoxserver
ezyhttp
ezyjpa
ezymq-kafka
ezyplatform
ezyredis
facebook
fe
filter
floating point
flutter
format json
freetank
front-end
frontend
fullstack
fulltextsearch
future
gallery
game
game-box
game-room
game-server
gateway
get
get file zip
git
glide
go
golang
gorilla
graduation thesis
graphql
grapql
grpc
guide
h2 database
handy terminal
hazelcast
hibernate
hibernateconfig
html
http
https
hyperloglog
image
index
indexing
integration-test
intellij
interface
io
ioc
ipfs
isolate
issue
it
java
java core
java spring
java web
javacore
javascript
javaw
jenkins
jetbrains
job
join
jotform
jpa
jpql
jquery
js
json
json file
json to object
jsonproperty
jsp
jsp & servlet
junit-test
jvm
jwt
kafka
keep promise
kerberos
keycloak
kotlin
languague
laravel
library
list
load balancer
load-balancing
lock
log
log4j
log4j-core
login
lỗi font
lưu trữ
machine learning
macos
mail
mail template
main
map
maria db
markdown
math
maven
merge
mermaid
message queue
messaging
metamask
microservice
microservices
migration
mobile
model
mongo
monitoring
mq
msgpack
multi-threading
multiple tenant
multithread
multithreading
mysql
n
naming
naming convention
nan
netcore
netty
network
networking
nft
nft game
nginx
nio
node.js
nodejs
non-blocking io
null
odoo
oop
opensource
optimize
oracle
orm
otp message
paginaiton
pagination
pancakeswap
panic
partition
pdf
pgpool
phỏng vấn
php
plugin
pointer
postgresql
postman
pre
private_key
procedure
profile
programming
programming-language
project management
promise
properties
push message android
push notification
push-noti
python
python unicode
qr
qrcode
question
queue
rabbitmq
react-native
reactive
reactjs
reactjs download
readmoretextview
recyclerview
redis
refactor
refresh token
regex
replica
repository
request
resilence4j
resource
rest
restful
resttemplate
roadmap
room database
ropssten
ropsten
round robin
rust
rxjava
s3
schedule
scheduled
scheduled spring boot
search
security
send email
send mail
serialization
server
servlet
session
shift jis
singleton
sjis
slack
smart contract
soap
socket
socket server
soft delete
solution
sosanh
spring
spring aop
spring boot
spring data jpa
spring redis
spring security
spring websocket
spring websocket cors
spring-boot-test
spring-jpa
springboot
springsecurity
springwebflux mysql
sql
sql server
sse
ssl
ssl email
stackask
storage
stream
stream api
stress test
stresstest
structure trong spring boot
study
synchronize
synchronized
system environment variables
tcp
test
thiết kế tầng trong dự án
thread
thread pool
threadjava
threadpool
thymeleaf
tomcat
totp
tracking location
transaction
transfer
transfer git
udp
ui
uniswap
unit test
unity
upload
upload file
utf-8 file
validate
validate date
vector
video call
vietqr
view
volatile
vue
vue cli
vuejs
watermark
web
web3
web3 client
webassembly
webflux
webpack
webrtc
websocket
windows 11
winforms
wordpress
work
xss
zip file
zookeeper