北京北大青鳥學校學術部提供:
使用Spring,可以使用里面的控制反轉把依賴對象交給Spring管理,并把依賴對象通過容器注入到組件內部。那么在Spring里面,該如何把對象注入到組件內部呢?北京北大青鳥學校學術部丁老師講解:
創建一個PersonDao對象,并把這個對象注入到PersonServiceBean中
Java代碼
1. package cn.accp.dao.impl;
2.
3. import cn.accp.dao.PersonDao;
4.
5. public class PersonDaoBean implements PersonDao {
6. public void add(){
7. System.out.println("執行PersonDaoBean里的add()方法");
8. }
9. }
面向接口編程,所以要把接口抽取出來。
Java代碼
1. package cn.accp.dao;
2.
3. public interface PersonDao {
4.
5. public void add();
6.
7. }
接口跟實現類不要放一塊,接下來,如何將PersonDaoBean對象注入進PersonServiceBean,北京北大青鳥學校丁老師表示注入方式有兩種:一種是構造器參數,另一種是通過屬性的set方法注入。 下面介紹通過屬性的set方法我們該如何注入PersonDaoBean對象
PersonServiceBean.java
Java代碼
1. package cn.accp.service.impl;
2.
3. import cn.accp.dao.PersonDao;
4. import cn.accp.service.PersonService;
5.
6. public class PersonServiceBean implements PersonService {
7. private PersonDao personDao;
8.
9. public PersonDao getPersonDao() {
10. return personDao;
11. }
12.
13. public void setPersonDao(PersonDao personDao) {
14. this.personDao = personDao;
15. }
16.
17. public void save(){
18. personDao.add();
19. }
20. }
北京北大青鳥學校丁老師:大家可以看到,在服務層的這個類里面,我們并沒有看到 PersonDaoBean的身影,也就是說我們并不關心這個實現類是誰,我們通過PersonDao這個接口去引用注入進來的對象,在通過接口調用它的 方法。這樣的話,服務層的組件和DAO層的組件已經進行徹底的解耦了。
看下在beans.xml里如何為personDao這個屬性注入PersonDaoBean這個bean呢? 首先要把personDao這個bean配置在Spring中
Xml代碼
1.
2.
4. xsi:schemaLocation="http://www.springframework.org/schema/beans
5. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
6.
7.
8.
9.
10.
property這個元素就是用于為屬性注入值,name填寫的是屬性的名稱
ref 填寫的值就是我們要注入的bean的名稱。Spring會根據這個名稱從Spring容器里面得到這個bean,因為這個bean默認在Spring容器 實例化后就會被實例化,所以它在容器里面根據ref里的名稱得到相應的bean,然后把這個bean通過反射技術就付給了
我們看下我們注入的personDao這個bean是否能夠成功注入呢? 北京北大青鳥學校丁老師提示:判斷是否能夠成功注入很簡單,在PersonServiceBean.java里的save方法,調用了personDao.add()方法,如果注入不 成功的話,就會出現空指針異常;如果能輸出add方法里面打印的那句話,就代表注入是成功的
Java代碼
1. package junit.test;
2.
3. import org.junit.BeforeClass;
4. import org.junit.Test;
5. import org.springframework.context.support.AbstractApplicationContext;
6. import org.springframework.context.support.ClassPathXmlApplicationContext;
7.
8. import cn.accp.service.PersonService;
9.
10. public class SpringTest {
11.
12. @BeforeClass
13. public static void setUpBeforeClass() throws Exception {
14. }
15.
16. @Test public void instanceSpring(){
17. AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
18. PersonService personService = (PersonService)ctx.getBean("personService");
19. personService.save();
20. ctx.close();
21. }
22. }
運行單元測試代碼,控制臺輸出“執行PersonDaoBean里的add()方法”。說明注入成功了。
北京北大青鳥學校提醒:大家思考下控制反轉這個概念,原先我們對象的創建是由應用本身創建的。現在對象的創建是由容器幫我們創建,并且由容器注入進來,這時候控制權發生了轉移,這就是所謂的控制反轉。