【SSH三大框架】Spring基礎第二篇:Spring依賴注入的三種方式
應用控制反轉,物件在被建立的時候,由一個調控系統內所有物件的外界實體將其所依賴的物件的引用傳遞給它。也可以說,依賴被注入到物件中。所以,控制反轉是,關於一個物件如何獲取他所依賴的物件的引用,這個責任的反轉。
對於依賴注入,有三種方式:
1、使用屬性的setter方法注入
2、使用構造器注入
3、使用註解注入
下面我們介紹下這三種方式:
一、使用屬性的setter方法注入
首先,我們寫一個PersonService.java介面
然後,我們為這個介面寫一個實現類:PersonServiceBean.javapublic interface PersonService { public abstract void save(); }
我們編輯beans.xml檔案,配置IOC反轉容器的xml程式碼:public class PersonServiceBean implements PersonService { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public void save(){ System.out.println(name); //personDao.add(); } }
我們寫了一個bean,並且定義了class屬性,在bean中,我們為“name”屬性設定了值:itcast<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"> <property name="name" value="itcast" /> </bean> </beans>
然後,我們寫一個測試類:SpringTest.java
public class SpringTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void instanceSpring() {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService personService = (PersonService)ctx.getBean("personService");
personService.save();
ctx.close();
}
}
當我們執行的時候,會打印出來itcast
原理:通過beans.xml我們配置了IOC反轉容器,配置的屬性通過setter方法進行注入。如果沒有setter方法會報錯。
二、使用構造器注入
首先,我們寫一個PersonDao.java介面
public interface PersonDao {
public void add();
}
並對這個介面進行實現:
public class PersonDaoBean implements PersonDao{
@Override
public void add() {
System.out.println("我是PersonDaoBean中的add()方法");
}
}
然後,我們寫一個PersonService.java介面:
public interface PersonService {
public void save();
}
並對這個介面進行實現:
public class PersonServiceBean implements PersonService {
private PersonDao personDao;
private String name;
public PersonServiceBean(){}
public PersonServiceBean(PersonDao personDao, String name) {
this.personDao = personDao;
this.name = name;
}
public PersonDao getPersonDao() {
return personDao;
}
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void save(){
personDao.add();
System.out.println(name);
//personDao.add();
}
}
可以看到,在這個實現類中,我們引入了一個PersonDao型別的屬性和一個String型別的屬性,並且建造了一個包含這兩個引數的建構函式和setter、getter方法。
然後,我們在beans.xml中進行配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean id="personDao" class="cn.itcast.dao.impl.PersonDaoBean"></bean>
<bean name="personService" class="cn.itcast.service.impl.PersonServiceBean">
<constructor-arg index="0" type="cn.itcast.dao.PersonDao" ref="personDao"></constructor-arg>
<constructor-arg index="1" value="itcast" />
</bean>
</beans>
可以看到,我們配置了兩個bean:
第一個bean是依賴bean,我們在PersonServiceBean.java類中需要依賴這個bean指向的類
第二個bean是我們要用到的bean,然後在這個bean中我們配置了兩個<constructor-arg>標籤:其中index表明索引,就是建構函式中引數的索引,0代表第一個引數;type表明這個引數的型別,ref表明需要依賴於哪個類。第二個中沒有type和ref,是因為String型別不需要指定type,另外也不是依賴類,所以也不需要ref屬性了。
然後,我們建立一個測試類:
package junit.test;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.service.PersonService;
public class SpringTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void instanceSpring() {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService personService = (PersonService)ctx.getBean("personService");
personService.save();
ctx.close();
}
}
可以打印出PersonServiceBean.java類中的save()方法中的東西。
三、使用註解注入
@Resource的作用相當於@Autowired,只不過@Autowired按byType自動注入,而@Resource預設按 byName自動注入罷了。@Resource有兩個屬性是比較重要的,分是name和type,Spring將@Resource註解的name屬性解析為bean的名字,而type屬性則解析為bean的型別。所以如果使用name屬性,則使用byName的自動注入策略,而使用type屬性時則使用byType自動注入策略。如果既不指定name也不指定type屬性,這時將通過反射機制使用byName自動注入策略。
@Resource裝配順序
1. 如果同時指定了name和type,則從Spring上下文中找到唯一匹配的bean進行裝配,找不到則丟擲異常
2. 如果指定了name,則從上下文中查詢名稱(id)匹配的bean進行裝配,找不到則丟擲異常
3. 如果指定了type,則從上下文中找到型別匹配的唯一bean進行裝配,找不到或者找到多個,都會丟擲異常
4. 如果既沒有指定name,又沒有指定type,則自動按照byName方式進行裝配;如果沒有匹配,則回退為一個原始型別進行匹配,如果匹配則自動裝配;
這裡僅僅使用@Resource進行舉例:
程式碼和上面的相同,僅僅是PersonServiceBean.java變了:
public class PersonServiceBean implements PersonService {
@Resource(name="personDao") private PersonDao personDao;
private String name;
public PersonDao getPersonDao() {
return personDao;
}
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void save(){
personDao.add();
}
}
可以看到,我們在private PersonDao personDao;這句話的前邊增加了@Resource(name="personDao")。
然後,我們看一下beans.xml配置檔案:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
<bean id="personDao" class="cn.itcast.dao.impl.PersonDaoBean"></bean>
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>
</beans>
我們增加了幾行程式碼:
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
然後,我們執行測試類,就可以打印出來了。
相關推薦
【SSH三大框架】Spring基礎第二篇:Spring依賴注入的三種方式
控制反轉(Inversion of Control)和依賴注入(Dependency Injection):應用控制反轉,物件在被建立的時候,由一個調控系統內所有物件的外界實體將其所依賴的物件的引用傳遞給它。也可以說,依賴被注入到物件中。所以,控制反轉是,關於一個物件如何獲
【SSH三大框架】Hibernate基礎第十二篇:load()懶載入分析以及一對一、一對多、多對一、多對多懶載入的分析
一、懶載入的定義: 懶載入:在WEB應用程式中,經常會需要查詢資料庫,系統的響應速度在很大程度上是與資料庫互動的響應。因此,如果能夠優化與資料庫的互動速度,則能夠大大提高WEB應用的響應速度。 例如:當有一個Student類和一個Teacher類。當我們載入一個學生的所有資
【SSH三大框架】Hibernate基礎第七篇:一對多關聯關係的操作
相對於上文的多對一關係,這裡又說明下一對多的關聯關係。 在上文中,我們描述了多對一的關係,在關係資料庫中也是多對一的關係,並且還是一對多的關係。但是,僅僅如此是不夠的,Hibernate是一種面向物件的結構,在Hibernate中仍然是多對一的關係,但是沒有一對多,所以我們
【SSH三大框架】Hibernate基礎第十三篇:lazy、constrained、fetch三個屬性的作用和使用方法
這三個屬性,個人感覺對於懶載入是很重要的,所以又重新開了一篇部落格來寫下這三個屬性的作用和使用方法 一、lazy屬性: lazy概念:只有真正使用該物件時,才會建立。對於hibernate而言,真正使用時才會發出SQL語句 1、在集合中定義: <set name
【SSH三大框架】Struts2基礎第三篇:配置Action以及呼叫Action的三種方式
一、struts.xml中的包和名稱空間 1、Struts2不支援為單獨的Action設定名稱空間,而是通過為包指定namespace屬性來為包下面的所有Action指定共同的名稱空間。 如果在配置<package>的時候沒有指定namespace屬性,則該包下
【SSH三大框架】Struts2基礎第七篇:log4j打印出日誌資訊
把這個歸於Struts2是不太合適的,因為log4j是一個開源的程式碼專案,不僅僅可以用在Struts2上。 我們介紹一下log4j:通過使用log4j,我們可以把一些資訊輸出到控制檯、文字檔案、html檔案等等中 首先,建立一個java project,我們建立一個li
Spring教程第二篇:Spring-Test(單元測試)
在Spring的框架下,做單元測試的兩種辦法: 一、使用spring中對Junit框架的整合功能 除了junit4和spring的jar包,還需要spring-test.jar。引入如下依賴: <dependency>
Spring 依賴注入三種方式的實現,及迴圈依賴問題的解決(原始碼+XML配置)
搬磚啦,搬磚啦,這幾天在看Spring相關的書,下面給大家分享一下這幾天的心得與收穫,Go Go Go! Spring支援兩種依賴注入方式,分別是屬性注入,建構函式注入。除此之外,Spring還支援工廠注入方式。 接下來,我們一起來了解一下Spring的幾種注入方式。
Mybatis【java三大框架】
三大框架和三層架構 ssm: SpringMVC Spring Framework Mybatis 三層架構: 表示層: 與客戶端實現互動。 &
【玩轉開源】BananaPi R2 —— 第二篇 Openwrt 網口配置分析
sign ati arr asi 1.0 tran spa 們的 errors 上次和大家分享了如何燒錄和安裝Openwrt到BananaPi R2,運行Openwrt的R2目前就具備路由器的功能了,這次我們來看看R2運行Openwrt的性能如何,同時也會講解一些常
【轉】Hadoop學習--第二篇:史上最詳細的Hadoop環境搭建
GitChat 作者:鳴宇淳 原文: 史上最詳細的Hadoop環境搭建 前言 Hadoop在大資料技術體系中的地位至關重要,Hadoop是大資料技術的基礎,對Hadoop基礎知識的掌握的紮實程度,會決定在大資料技術道路上走多遠。 這是一篇入門文章,Hadoop的學
【Spring學習筆記】7:裝配bean的三種方式(自動裝配,JavaConfig,XML),配置匯入
跟著《Spring實戰》徹底系統地學習一下Spring。 對Spring的新認識 Spring的關鍵 基於POJO的輕量級和最小侵入性程式設計。 通過DI和麵向介面實現鬆耦合。 基於切面和慣例進行宣告式程式設計。 通過切面和模板減少樣板式程式碼。 所
SpringBoot非官方教程 | 第二篇:Spring Boot配置檔案詳解
springboot採納了建立生產就緒Spring應用程式的觀點。 Spring Boot優先於配置的慣例,旨在讓您儘快啟動和執行。在一般情況下,我們不需要做太多的配置就能夠讓spring boot正常執行。在一些特殊的情況下,我們需要做修改一些配置,或者需要有自己的配置屬性。 當我們
【圖解資料結構】 一組動畫徹底理解二叉樹三種遍歷
二叉樹的遍歷是指從根結點出發,按照某種次序依次訪問二叉樹中所有結點,使得每個結點被訪問一次且僅被訪問一次。 在二叉樹的遍歷中存在三種較為常用的遍歷方式:前序遍歷、中序遍歷、後序遍歷。接下來我將嘗試著用三組動畫向讀者詳細的介紹這三種遍歷方式的邏輯思路,希望讓讀者看到任何的二叉樹都能在腦海中快速的勾勒出動畫。
SpringBoot學習第二篇:Spring Boot配置檔案詳解
原文首發於:https://www.fangzhipeng.com/springboot/2017/07/11/springboot2-config-file/ 本文出自方誌朋的部落格 springboot採納了建立生產就緒Spring應用程式的觀點。 Spring Boot優先於配置的慣例,旨
第二篇:Spring Boot配置檔案詳解
Spring Boot採納了建立生產就緒Spring應用程式的觀點。 Spring Boot優先於配置的慣例,旨在讓您儘快啟動和執行。在一般情況下,我們不需要做太多的配置就能夠讓Spring Boot正常執行。在一些特殊的情況下,我們需要做一些配置修改,或者配置自定義屬性。 自定義屬
轉載:SpringBoot非官方教程 | 第二篇:Spring Boot配置檔案詳解
springboot採納了建立生產就緒Spring應用程式的觀點。 Spring Boot優先於配置的慣例,旨在讓您儘快啟動和執行。在一般情況下,我們不需要做太多的配置就能夠讓spring boot正常執行。在一些特殊的情況下,我們需要做修改一些配置,或者需要
Python3基礎第二篇:不可變序列操作
不可變的序列包含元組(tuple)、range()函式、str文字序列。 讓我們先來看看元組吧------>>> tuple是可包含任意物件的有序集合、通過下標訪問元素,任意巢狀儲存。
易筋SpringBoot2.1 | 第二篇:Spring Boot配置檔案詳解
寫作時間:2018-12-22 Spring Boot: 2.1 ,JDK: 1.8, IDE: IntelliJ IDEA, 配置檔案說明 Spring Boot 配置檔案允許為同一套應用,為不同的環境用不同的配置檔案。比如開發環境、測試環境、生成環境。你可以用properties
第二篇:Spring Cloud Eureka 服務註冊+發現
Spring Cloud Netflix 主要元件 Spring Cloud Netflix 的核心是用於服務註冊與發現的 Eureka,接下來我們將以 Eureka 為線索,介紹 Eureka、Ribbon、Hystrix、Feign 這些 Spring Cloud Netflix 主要元件。 服務註冊