spring中IoC和DI的示例分析

這篇文章主要介紹spring中IoC和DI的示例分析,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

為隴西等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計(jì)制作服務(wù),及隴西網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為成都做網(wǎng)站、成都網(wǎng)站建設(shè)、隴西網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會得到認(rèn)可,從而選擇與我們長期合作。這樣,我們也可以走得更遠(yuǎn)!

這里先來簡單介紹下IoC和DI的區(qū)別:

IOC:翻譯過來是控制反轉(zhuǎn),將對象的創(chuàng)建權(quán)由Spring管理,HelloService不需要自己去創(chuàng)建,Spring可以幫你創(chuàng)建。

DI:依賴注入,在我們創(chuàng)建對象的過程中,把對象依賴的屬性注入到我們的類中。

我們現(xiàn)在編寫的類是沒有其它的屬性的,如果你學(xué)過UML這種設(shè)計(jì)的話,面向?qū)ο笾袑ο笾械膸追N關(guān)系

簡單來書,IoC更像是一種思想,DI是一種行為。

另一種說法是,ioc是目的,di是手段。ioc是指讓生成類的方式由傳統(tǒng)方式(new)反過來,既程序員不調(diào)用new,需要類的時(shí)候由框架注入(di),是同一件不同層面的解讀。

IoC:Inverse of Control(控制反轉(zhuǎn)):

將原本在程序中手動創(chuàng)建對象的控制權(quán),交由Spring框架來管理。

Spring第一個(gè)spring測試程序

1.準(zhǔn)備jar包

spring-beans-4.1.2.RELEASE.jar
spring-core-4.1.2.RELEASE.jar
com.springsource.org.apache.commons.logging-

public class HelloSpring {
	@Setter //必須有set屬性
	private String name;
	public void say() {
		System.out.println("hello---" + name);
	}
}
@Test
//把創(chuàng)建的對象交給spring框架管理
public void test1() throws Exception {
	//1讀取資源文件
	Resource resource = new ClassPathResource("/applicationContext.xml");
	//2創(chuàng)建spring容器對象
	BeanFactory bf = new XmlBeanFactory(resource);
	//3從srping容器中獲得指定名稱對象
	HelloSpring hello = bf.getBean("helloSpring", HelloSpring.class);

配置applicateion.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"
xsi:schemaLocation="
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<beans>
  <bean name="helloSpring" class="全限定類名">
    <property name="需要注入的屬性名稱" value="注入值" />
  </bean>
</beans>

使用import元素引入其他的配置文件:

<import resource="classpath:bin目錄文件路徑"/>

使用import元素注意:

1、默認(rèn)情況下,從classpath的跟路徑尋找。
2、可以使用前綴來定位文件的基礎(chǔ)位置:

①:[classpath:]:后面的文件從classpath路徑開始找(推薦);[注意classloader的問題。]
②:[file:]:后面的文件使用文件系統(tǒng)的路徑開始找;

注意:只有當(dāng)框架中實(shí)現(xiàn)了Resource接口才能夠識別上述的前綴標(biāo)識符。

Spring中的測試

Spring測試環(huán)境準(zhǔn)備:

依賴jar:

1.spring-test-4.1.2.RELEASE.jar
2.spring-context-4.1.2.RELEASE.jar
3.spring-aop-4.1.2.RELEASE.jar
4.spring-expression-4.1.2.RELEASE.jar

Spring4.x需要依賴的單元測試得是最新的junit4.12,Eclipse自帶的junit4.8不支持,同時(shí)從Spring4.x開始,還得依賴AOP包的支持。

junit-4.12.jar
hamcrest-core-1.3.jar

@RunWith(SpringJUnit4ClassRunner.class)表示先啟動Spring容器,把junit運(yùn)行在Spring容器中
@ContextConfiguration("classpath:applicationContext.xml"):表示從哪里加載資源文件
public class HelloWorldTest {
	@Autowired :表示自動裝配
	private BeanFactory factory;
	@Test
	public void testSpringTest() throws Exception {
		HelloWorld helloWorld = factory.getBean("springTest", HelloWorld.class);
		helloWorld.sayHello();
	}
}

把@ContextConfiguration(“classpath:applicationContext.xml”) 寫成@ContextConfiguration
默認(rèn)去找的當(dāng)前測試類名-context.xml配置文件,如:HelloWorldTest-context.xml

Spring容器

BeanFactory:是Spring中最底層的接口,只提供了最簡單的IoC功能(創(chuàng)建和管理bean)。

在應(yīng)用中,一般不使用BeanFactory,而推薦使用ApplicationContext(應(yīng)用上下文),原因如下。

被Spring所管理的成員都稱之為bean(類,對象,bean元素).

BeanFactory和ApplicationContext的區(qū)別

1、ApplicationContext繼承了BeanFactory,擁有了基本的IoC功能;
2、除此之外,ApplicationContext還提供了以下的功能:

①、支持國際化;
②、支持消息機(jī)制;
③、支持統(tǒng)一的資源加載;
④、支持AOP功能;

bean的創(chuàng)建時(shí)機(jī):

1.ApplicationContext在加載的時(shí)候就會創(chuàng)建所有的bean(Web應(yīng)用建議).
2.BeanFactory需要等到拿bean的時(shí)候才會創(chuàng)建bean(桌面程序),延遲初始化.

//針對于當(dāng)前xml中所有的bean:是否需要延遲初始化.
<bean lazy-init="default | false | true"> 
//針對于指定的bean:是否需要延遲初始化.
<beans default-lazy-init="default | false | true">

bean的作用域,bean對象可以存活多久

<bean id="" class="" scope="作用域"/>
singleton: 單例 ,在Spring IoC容器中僅存在一個(gè)Bean實(shí)例 (默認(rèn)的scope)
prototype: 多例 ,每次從容器中調(diào)用Bean時(shí),都返回一個(gè)新的實(shí)例,即每次調(diào)用getBean()時(shí) ,相當(dāng)于執(zhí)行new XxxBean():不會在容器啟動時(shí)創(chuàng)建對象
request: 用于web開發(fā),將Bean放入request范圍 ,request.setAttribute("xxx") , 在同一個(gè)request 獲得同一個(gè)Bean
session: 用于web開發(fā),將Bean 放入Session范圍,在同一個(gè)Session 獲得同一個(gè)Bean 
globalSession: 一般用于Porlet應(yīng)用環(huán)境 , 分布式系統(tǒng)存在全局session概念(單點(diǎn)登錄),如果不是porlet環(huán)境,globalSession 等同于Session 
對于Struts2中的Action使用prototype類型,其他使用singleton

DI:Dependency Injection:
依賴注入介紹 和XML的自動裝配
指Spring創(chuàng)建對象的過程中,將對象依賴屬性通過配置進(jìn)行注入
xml方式-自動裝配(一般不推薦使用):

<bean />元素的:autowire屬性
<bean id="somebean" class="SomeBean全限定名" autowire="byType"/>

autowire屬性:讓spring按照一定的方式自己去找合適的對象,并完成DI

- default:不要自動注入
- no:不要自動注入
- byName:按照名字注入(按照屬性的名字在spring中找bean) factory.getBean(“屬性的名字”)
- byType:按照依賴對象的類型注入(factory.getBean(屬性的類型))
- constructor:按照對象的構(gòu)造器上面的參數(shù)類型注入

注意:

1,如果按照byName自動注入,要求所有的屬性名字和id的名字必須保證一種規(guī)范的命名方式;
2,如果按照byType注入,如果spring中同一個(gè)類型有多個(gè)實(shí)例-->報(bào)bean不是唯一類型錯(cuò)誤;

手動裝配:

屬性注入: 通過對象的setter方法注入依賴的對象.

使用setter注入:
1,使用bean元素的子元素設(shè)置;
1,簡單類型值,直接使用value賦值;
2,引用類型,使用ref賦值;
3,集合類型,直接使用對應(yīng)的集合類型元素即可。
2,spring通過屬性的setter方法注入值;
3,在配置文件中配置的值都是string,spring可以自動的完成類型的轉(zhuǎn)換
4,屬性的設(shè)置值是在init方法執(zhí)行之前完成的
5,改進(jìn)spring的測試,直接在測試類里面注入需要測試的對象

//實(shí)體類
@Setter
public class Employee {
	private String name;
}
//測試類
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class EmployeeTest {
	@Autowired
	  private ApplicationContext ctx;
	@Test
	  public void test1() throws Exception {
		Employee bean = ctx.getBean("employee", Employee.class);
		System.out.println(bean);
	}
}
//application配置
<bean id="employee" class="com.***.Employee">
  <property name="name" value="zoe" />
</bean>

構(gòu)造器注入: 通過構(gòu)造器,在創(chuàng)建對象的時(shí)候就注入依賴對象

constructor-arg:構(gòu)造器參數(shù)

1,spring在實(shí)例化對象的時(shí)候,如果對象沒有配置constructor-arg,則使用默認(rèn)的構(gòu)造器實(shí)例化對象
2,如果有constructor-arg,那么spring使用這些constructor-arg來唯一確定一個(gè)構(gòu)造器
1,默認(rèn)情況下,constructor-arg的順序就是構(gòu)造器參數(shù)的順序
2,3中調(diào)整構(gòu)造器順序:
1.index:在構(gòu)造器中的參數(shù)位置
2.type:在構(gòu)造器中的參數(shù)的類型
3.name:在構(gòu)造器中按照構(gòu)造器的參數(shù)名字設(shè)置值

使用哪種注入方式比較好(setter?構(gòu)造器?)?

1,如果一個(gè)類必須依賴另一個(gè)類才能正常運(yùn)行,用構(gòu)造器;
2,但是構(gòu)造器的參數(shù)如果過多,構(gòu)造器很難看;
3,更多的還是使用setter注入;
4,可以使用@Required標(biāo)簽來要求一個(gè)屬性必須注入

public class Employee {
  private String name;
  public Employee(String name) {
    this.name = name;
  }
}
//application配置
<bean id="employee" class="com.***.Employee">
  <constructor-arg name="name" value="zoe" />
</bean>

屬性占位符(property place holder)

spring屬性占位符之創(chuàng)建連接池對象

依賴的jar:>>MySQL驅(qū)動包>>druid包.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class PropertyPlaceHolderTest {
  @Autowired
  private DataSource ds ;

  @Test
  public void testLink() throws Exception {
    Connection conn = ds.getConnection();
    String sql = "select * from user";
    PreparedStatement ps = conn.prepareStatement(sql);
    ResultSet rs = ps.executeQuery();
  }
}

application配置文件

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context.xsd
  ">
<!-- 加載 properties -->
<!-- system-properties-mode="NEVER" 不使用系統(tǒng)默認(rèn)屬性 -->
<context:property-placeholder location="classpath:db.properties"
  system-properties-mode="NEVER" />

<!-- 配置連接池 -->
<bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
  <property name="driverClassName" value="${jdbd.driverClassName}" />
  <property name="url" value="${jdbd.url}" />
  <property name="jdbd.username" value="${username}" />
  <property name="jdbd.password" value="${password}" />
</bean>
</beans>

db.properties文件

jdbd.driverClassName=com.mysql.jdbc.Driver
jdbd.url=jdbc:mysql:///springdemo
jdbd.username=root
jdbd.password=admin

以上是“spring中IoC和DI的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

網(wǎng)站欄目:spring中IoC和DI的示例分析
標(biāo)題鏈接:http://www.muchs.cn/article22/ippjjc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作、小程序開發(fā)響應(yīng)式網(wǎng)站、建站公司、云服務(wù)器、定制網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)