Dependency Injection và Inversion of Control trong Spring Framework là hai khái niệm khá trừu tượng và khó hiểu kể cả các lập trình viên mới và cố kinh nghiệm.Hiện có rất nhiều bài viết về Dependency Injection và Inversion of Control,mỗi người lại có một cách giải thích khác nhau.Tuy nhiên ở bài này,mình sẽ giải thích và tổng hợp cũng như cố gắng để các bạn dễ hiểu về hai khái niệm Dependency Injection và Inversion of Control này.
Khái niệm Dependency Injection và Inversion of Control
1.Inversion of control (IOC)
Inversion of control hay viết tắc của IOC đó chính là khả năng của Spring container trong việc quản lý các thành phần, khi mà thay vì một thành phần phải tự đòi hỏi các tài nguyên cho nó, thì nó sẽ được Spring container cung cấp các tài nguyên dựa vào thông tin trong file cấu hình.
2. Dependency Injection (DI)
Dependency Injection hay viết tắt của DI,là khả năng liên kết giữa các thành phần lại với nhau trong Spring, đó chính là việc các thuộc tính trong một đối tượng được “tiêm chích” để tham chiếu lần lượt đến các đối tượng khác được quản lý bởi Spring container.
Với Dependency Injection thì một đối tượng sẽ không phụ thuộc và đối tượng khác và đối tượng khác cũng vậy. Khi cần đối tượng này sẽ gọi tới đối tượng kia và ngược lại. Và mình đã hỏi các bạn, các đối tượng sẽ được tạo ra và nằm ở đâu để khi cần chúng có thể gọi lẫn nhau. Câu trả lời là chúng ta phải có một khung chứa, và khung chứa đó chính là một phần của IoC.
Ví dụ
Ví dụ về Dependency Injection
Để các bạn có thể hiểu hơn về DI mình sẽ viết một ví dụ như sau :
Đây là cách bạn tạo sự phụ thuộc đối tượng trong các chương trình truyền thống:
1 2 3 4 5 6 7 |
public class Store { private Item item; public Store() { item = new ItemImpl1(); } } |
Trong ví dụ trên, bạn có thể thấy rằng,để nhanh chóng sự phụ thuộc item của đối tượng Store, bạn phải xác định việc thực hiện giao diện Item nào chúng ta sẽ sử dụng trong lớp Store .
Bằng cách sử dụng DI, chúng ta có thể viết lại ví dụ mà không nêu rõ việc thực hiện của Item mà chúng ta muốn:
1 2 3 4 5 6 |
public class Store { private Item item; public Store(Item item) { this.item = item; } } |
Việc triển khai Item được Injection (tiêm) sẽ được cung cấp thông qua metadata.

Với Dependency Injection (DI) thì chúng ta có hai cách để Injection data.Đó chính là :
-
Setter Injection
-
Constructor Injection
Để hiểu rõ hơn về khái niệm này,các bạn có thể đọc bài viết chi tiết tại đây.
Chúng ta sẽ cùng nhau tìm hiểu về ví dụ hai khái niệm trên :
- Sử dụng Setter Injection
User.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package entites; public class User { private int id_user; private String username; private String password; public int getId_user() { return id_user; } public void setId_user(int id_user) { this.id_user = id_user; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } |
mvc-dispatcher-servlet.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context "> <context:annotation-config /> <context:component-scan base-package="controller" /> <bean id="jspviewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <bean id="user1" class="entites.User"> <property name="username" value="itphutran"></property> </bean> </beans> |
TestController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import entites.User; @Controller public class TestController { @Autowired private User user; @RequestMapping(value ="/test", method = RequestMethod.GET) public String login() { System.out.println(user.getUsername()); System.out.println(user.getPassword()); return ""; } } |
Output: itphutran null
- Sử dụng Constructor Injection
Tương tự chúng ta cũng có những file cấu hình trên,tuy nhiên cần phải thay đổi trong file mvc-dispatcher-servlet.xml.
mvc-dispatcher-servlet.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context "> <context:annotation-config /> <context:component-scan base-package="controller" /> <bean id="jspviewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <bean id="user1" class="entites.User"> <constructor-arg type="int" value="1" ></constructor-arg> <constructor-arg type="String" value="itphutran" name="username" ></constructor-arg> <constructor-arg type="String" value="password" name="password" ></constructor-arg> </bean> </beans> |
Output:1, itphutran ,password.
Tổng kết :
Qua những khái niệm và ví dụ trên,bạn đọc cũng đã hiểu hơn về Dependency Injection và Inversion of Control trong Spring Framework.Hy vọng sẽ giúp ích cho các bạn ứng dụng và phát triển các project sau này.Share bài viết để mọi người cùng đọc nhé.
wh0cd283556 [url=http://tadalafil18.us.org/]tadalafil[/url]
Thanks for sharing such a fastidious idea, article is nice,
thats why i have read it entirely
I really like what you guys tend to be up too.
This kind of clever work and reporting! Keep up the terrific works guys I’ve incorporated you
guys to blogroll.
Attractive section of content. I just stumbled upon your website and
in accession capital to assert that I acquire actually enjoyed account your blog posts.
Anyway I’ll be subscribing to your augment and even I achievement you
access consistently quickly.
Hey! This is my first visit to your blog! We are a team of
volunteers and starting a new project in a community in the same niche.
Your blog provided us useful information to work on. You have done a outstanding job!
Good day! Do you know if they make any plugins to assist with Search Engine
Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good gains.
If you know of any please share. Appreciate
it!
Superb blog! Do you have any recommendations for aspiring writers?
I’m hoping to start my own site soon but I’m a little lost on everything.
Would you recommend starting with a free platform like
Wordpress or go for a paid option? There are so many choices out
there that I’m totally confused .. Any tips?
Thanks!
Excellent post! We are linking to this particularly great article
on our website. Keep up the great writing.
There’s definately a great deal to find out about this topic.
I really like all of the points you’ve made.
Having read this I thought it was really enlightening. I appreciate you spending some time and energy to put this short article
together. I once again find myself spending a lot of time both reading and commenting.
But so what, it was still worth it!
Hi colleagues, nice piece of writing and nice urging commented at this place, I
am genuinely enjoying by these.
Great info. Lucky me I came across your site by chance (stumbleupon).
I’ve book-marked it for later!
Greetings from Florida! I’m bored to tears at work so I decided to
check out your site on my iphone during lunch break. I really like the information you provide here and can’t wait to take a look when I
get home. I’m amazed at how quick your blog loaded on my phone ..
I’m not even using WIFI, just 3G .. Anyways, awesome blog!
Everyone loves it when individuals come together and share views.
Great blog, stick with it!
Howdy very nice web site!! Man .. Excellent .. Amazing ..
I’ll bookmark your website and take the feeds also? I’m
happy to seek out numerous useful info right here in the put up,
we want develop extra techniques in this regard, thank you for sharing.
. . . . .
301 Moved Permanently [url=https://www.918online.today/category/sky777/]Click here…[/url]
Greetings from the real universe.
Fantastic website. A lot of helpful info here. I’m sending it to several friends ans also sharing in delicious.
And certainly, thank you in your sweat!
Hi there! I know this is kind of off topic but I was wondering if you knew where I could get a captcha
plugin for my comment form? I’m using the same blog platform as yours and I’m having difficulty finding one?
Thanks a lot!