Spring詳解(三)

Spring詳解(三)

DI依賴注入

spring動態(tài)的向某個對象提供它所需要的其他對象搔啊。這一點是通過DI(Dependency Injection洒试,依賴注入)來實現(xiàn)的规肴。比如對象A需要操作數(shù)據(jù)庫鲁冯,以前我們總是要在A中自己編寫代碼來獲得一個Connection對象垃帅,有了 spring我們就只需要告訴spring缨叫,A中需要一個Connection椭符,至于這個Connection怎么構(gòu)造,何時構(gòu)造耻姥,A不需要知道销钝。在系統(tǒng)運行時,spring會在適當?shù)臅r候制造一個Connection琐簇,然后像打針一樣蒸健,注射到A當中,這樣就完成了對各個對象之間關(guān)系的控制婉商。A需要依賴 Connection才能正常運行似忧,而這個Connection是由spring注入到A中的,依賴注入的名字就這么來的丈秩。

import java.util.List;

import java.util.Map;

import java.util.Properties;

import java.util.Set;

public class Person {

private Long pid;

private String pname;

private Student students;

private List lists;

private Set sets;

private Map maps;

private Properties properties;

}

在 applicationContext.xml 中進行賦值

<!--

property是用來描述一個類的屬性

基本類型的封裝類盯捌、String等需要值的類型用value賦值

引用類型用ref賦值

-->

<bean id="person" class="com.my.di.Person">

<property name="pid" value="1"></property>

<property name="pname" value="vae"></property>

<property name="students">

<ref bean="student"/>

</property>

<property name="students" ref="student">//注入bean

<property name="students.name" value="jack">//級聯(lián)private Student students=new Student()

</property>

<property name="lists">

<list>

<value>1</value>

<ref bean="student"/>

<value>vae</value>

</list>

</property>

<property name="sets">

<set>

<value>1</value>

<ref bean="student"/>

<value>vae</value>

</set>

</property>

<property name="maps">

<map>

<entry key="m1" value="1"></entry>

<entry key="m2" >

<ref bean="student"/>

</entry>

</map>

</property>

<property name="properties">

<props>

<prop key="p1">p1</prop>

<prop key="p2">p2</prop>

</props>

</property>

</bean>

<bean id="student" class="com.my.di.Student"></bean>

//利用 set 方法給對象賦值

@Test

public void testSet(){

//1、啟動 spring 容器

//2蘑秽、從 spring 容器中取出數(shù)據(jù)

//3饺著、通過對象調(diào)用方法

ApplicationContext context =

new ClassPathXmlApplicationContext("applicationContext.xml");

Person person = (Person) context.getBean("person");

System.out.println(person.getPname());//vae

}

利用 構(gòu)造函數(shù) 給屬性賦值

在實體類 Person.java 中添加兩個構(gòu)造方法:有參和無參

//默認構(gòu)造函數(shù)

public Person(){}

//帶參構(gòu)造函數(shù)

public Person(Long pid,Student students){

this.pid = pid;

this.students = students;

}

在 applicationContext.xml 中進行賦值

<!-- 根據(jù)構(gòu)造函數(shù)賦值 -->

<!--

index 代表參數(shù)的位置 從0開始計算

type 指的是參數(shù)的類型,在有多個構(gòu)造函數(shù)時,可以用type來區(qū)分肠牲,要是能確定是那個構(gòu)造函數(shù)瓶籽,可以不用寫type

value 給基本類型賦值

ref 給引用類型賦值

-->

<bean id="person_con" class="com.my.di.Person">

<constructor-arg index="0" type="java.lang.Long" value="1">

</constructor-arg>

<constructor-arg index="1" type="com.my.di.Student" ref="student_con"></constructor-arg>

</bean>

<bean id="student_con" class="com.my.di.Student"></bean>

//利用 構(gòu)造函數(shù) 給對象賦值

@Test

public void testConstrutor(){

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

Person person = (Person) context.getBean("person_con");

System.out.println(person.getPid());//1

}

  1、如果spring的配置文件中的bean中沒有<constructor-arg>該元素埂材,則調(diào)用默認的構(gòu)造函數(shù)

  2、如果spring的配置文件中的bean中有<constructor-arg>該元素汤求,則該元素確定唯一的構(gòu)造函數(shù)

構(gòu)造方法通過類型注入

public class People {

private int id;

private String name;

private int age;

public People() {

super();

// TODO Auto-generated constructor stub

}

public People(int id, String name, int age) {

super();

this.id = id;

this.name = name;

this.age = age;

}

}

<bean id="people3" class="com.java.entity.People">

<constructor-arg type="int" value="2"></constructor-arg>

<constructor-arg type="String" value="李四"></constructor-arg>

<constructor-arg type="int" value="22"></constructor-arg>

</bean>

自動裝配

byName通過名稱自動匹配

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

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.xsd"

default-autowire="byName">

<bean id="dog" class="com.java.entity.Dog">

<property name="name" value="Jack"></property>

</bean>

<bean id="dog2" class="com.java.entity.Dog">

<property name="name" value="Tom"></property>

</bean>

<bean id="people1" class="com.java.entity.People">

<property name="id" value="1"></property>

<property name="name" value="張三"></property>

<property name="age" value="11"></property>

</bean>

</beans>

public class People {

private int id;

private String name;

private int age;

private Dog dog;

}


byType:通過類型進行自動匹配

constructor;根據(jù)類型俏险,自動注入

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

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.xsd"

default-autowire="constructor">

<bean id="dog" class="com.java.entity.Dog">

<property name="name" value="Jack"></property>

</bean>

<bean id="people1" class="com.java.entity.People">

<property name="id" value="1"></property>

<property name="name" value="張三"></property>

<property name="age" value="11"></property>

</bean>

</beans>

public class People {

private int id;

private String name;

private int age;

private Dog dog;

public People() {

super();

// TODO Auto-generated constructor stub

}

public People(Dog dog) {

super();

System.out.println("constructor");

this.dog = dog;

}

}

bean之間的關(guān)系

繼承

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

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.xsd">

<bean id="dog" class="com.java.entity.Dog">

<property name="name" value="jack"></property>

</bean>

<bean id="abstractPeople" class="com.java.entity.People" abstract="true">

<property name="className" value="高三5班"></property>

<property name="age" value="19"></property>

</bean>

<bean id="zhangsan" parent="abstractPeople" depends-on="autority">

<property name="id" value="1"></property>

<property name="name" value="張三"></property>

</bean>

<bean id="lisi" parent="abstractPeople">

<property name="id" value="2"></property>

<property name="name" value="李四"></property>

<property name="age" value="20"></property>

<property name="dog" ref="dog"></property>

</bean>

<bean id="autority" class="com.java.service.Authority"></bean>

</beans>

public class T {

private ApplicationContext ac;

@Before

public void setUp() throws Exception {

ac=new ClassPathXmlApplicationContext("beans.xml");

}

@Test

public void test1() {

People zhangsan=(People)ac.getBean("zhangsan");

System.out.println(zhangsan);

People lisi=(People)ac.getBean("lisi");

System.out.println(lisi);

}

}

依賴

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

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.xsd">

<bean id="dog" class="com.java.entity.Dog">

<property name="name" value="jack"></property>

</bean>

<bean id="zhangsan" parent="abstractPeople" depends-on="autority">

<property name="id" value="1"></property>

<property name="name" value="張三"></property>

</bean>

<bean id="lisi" parent="abstractPeople">

<property name="id" value="2"></property>

<property name="name" value="李四"></property>

<property name="age" value="20"></property>

<property name="dog" ref="dog"></property>

</bean>

<bean id="autority" class="com.java.service.Authority"></bean>

</beans>

使用注解,讓 Spring 容器幫我們產(chǎn)生 Person 對象

使用注解

在 applicationContext.xml 中引入命名空間

引入的命名空間扬绪,簡單來說就是用來約束xml文件格式的竖独。第一個 xmlns:context ,這表示標簽格式應(yīng)該是 <context:標

在 applicationContext.xml 文件中引入注解掃描器

<!-- 組件掃描挤牛,掃描含有注解的類 -->

<context:component-scan base-package="com.my.annotation"></context:component-scan>

base-package:表示含有注解類的包名

  如果掃描多個包莹痢,則上面的代碼書寫多行,改變 base-package 里面的內(nèi)容即可!

@Component

  如果一個類上加了@Component注解竞膳,就會進行如下的法則

      如果其value屬性的值為""

       @Component

       public class Person {}

        等價于

      <bean id="person" class="..Person">

       如果其value屬性的值不為""

       @Component("p")

      public class Person {}

        等價于

      <bean id="p" class="..Person">

在 Person 類中添加注解@Component


public void testAnnotation(){

//1航瞭、啟動 spring 容器

//2、從 spring 容器中取出數(shù)據(jù)

//3坦辟、通過對象調(diào)用方法

ApplicationContext context =

new ClassPathXmlApplicationContext("applicationContext.xml");

Person person = (Person) context.getBean("person");

System.out.println(person.getPname());

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末刊侯,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子锉走,更是在濱河造成了極大的恐慌滨彻,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件挪蹭,死亡現(xiàn)場離奇詭異亭饵,居然都是意外死亡,警方通過查閱死者的電腦和手機梁厉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進店門辜羊,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人懂算,你說我怎么就攤上這事只冻。” “怎么了计技?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵喜德,是天一觀的道長。 經(jīng)常有香客問我垮媒,道長舍悯,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任睡雇,我火速辦了婚禮萌衬,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘它抱。我一直安慰自己秕豫,他們只是感情好,可當我...
    茶點故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布观蓄。 她就那樣靜靜地躺著混移,像睡著了一般。 火紅的嫁衣襯著肌膚如雪侮穿。 梳的紋絲不亂的頭發(fā)上歌径,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天,我揣著相機與錄音亲茅,去河邊找鬼回铛。 笑死狗准,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的茵肃。 我是一名探鬼主播腔长,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼免姿!你這毒婦竟也來了饼酿?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤胚膊,失蹤者是張志新(化名)和其女友劉穎故俐,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體紊婉,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡药版,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了喻犁。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片槽片。...
    茶點故事閱讀 39,919評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖肢础,靈堂內(nèi)的尸體忽然破棺而出还栓,到底是詐尸還是另有隱情,我是刑警寧澤传轰,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布剩盒,位于F島的核電站,受9級特大地震影響慨蛙,放射性物質(zhì)發(fā)生泄漏辽聊。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一期贫、第九天 我趴在偏房一處隱蔽的房頂上張望跟匆。 院中可真熱鬧,春花似錦通砍、人聲如沸玛臂。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽垢揩。三九已至,卻和暖如春敛瓷,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背斑匪。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工呐籽, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留锋勺,地道東北人。 一個月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓狡蝶,卻偏偏與公主長得像庶橱,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子贪惹,可洞房花燭夜當晚...
    茶點故事閱讀 44,864評論 2 354

推薦閱讀更多精彩內(nèi)容