Spring.net 作為一個(gè)應(yīng)用程序框架,在構(gòu)建企業(yè)級(jí).net應(yīng)用程序提供了很多靈活而又豐富的功能(如:依賴注入,aop,數(shù)據(jù)訪問(wèn)抽象,asp.net 擴(kuò)展)。
Inversion of Control:簡(jiǎn)稱IoC :是面向?qū)ο缶幊讨械囊环N設(shè)計(jì)原則,可以用來(lái)減低計(jì)算機(jī)代碼之間的耦合度。其中最常見(jiàn)的方式叫做依賴注入(Dependency Injection,簡(jiǎn)稱DI),還有一種方式叫“依賴查找”(Dependency Lookup)。通過(guò)控制反轉(zhuǎn),對(duì)象在被創(chuàng)建的時(shí)候,由一個(gè)調(diào)控系統(tǒng)內(nèi)所有對(duì)象的外界實(shí)體,將其所依賴的對(duì)象的引用傳遞給它。也可以說(shuō),依賴被注入到對(duì)象中。
個(gè)人理解:根據(jù)面向?qū)ο笾袑?duì)象的父子繼承,接口或抽象的實(shí)現(xiàn)等,對(duì)持有關(guān)系的對(duì)象的實(shí)例化進(jìn)行控制。
有一只寵物:
public interface Pet { string name { get; set; } void bark(); }小狗:
public class Dog : Pet { public string name { get; set; } public void bark() { Console.WriteLine("汪汪汪汪汪汪汪汪汪..."); } }人:
public class Person { public string name { get; set; } public Pet pet { get; set; } }項(xiàng)目引用:spring.core --整個(gè)框架的基礎(chǔ),實(shí)現(xiàn)了依賴注入的功能
Spring.AOP--提供面向方面編程(aop)的支持
Spring.Data--a定義了一個(gè)抽象的數(shù)據(jù)訪問(wèn)層,可以跨越各種數(shù)據(jù)訪問(wèn)技術(shù)(從ADO.NET到各種orm)進(jìn)行數(shù)據(jù)訪問(wèn)。
項(xiàng)目配置文件:app.config
<?xml version="1.0" encoding="utf-8" ?><configuration> <configSections> <sectionGroup name="spring"> <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core" /> <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" /> </sectionGroup> </configSections> <spring> <context> <resource uri="file://objects.xml"></resource> </context> <objects xmlns="http://www.springframework.net"> </objects> </spring></configuration>
objects.xml 屬性為始終復(fù)制,不然上面配置的<resource uri="file://objects.xml"></resource>找不到。
<?xml version="1.0" encoding="utf-8" ?><objects xmlns="http://www.springframework.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd"> <object id="person" type="SpringDemo.Person,SpringDemo" singleton="true" > <property name="pet" ref="dog" ></property> <property name="name" value="Yahue"></property> </object> <object id="dog" type="SpringDemo.Dog,SpringDemo" singleton="true"> <property name="name" value="旺財(cái)"></property> </object></objects>
控制臺(tái)程序中:
static void fistIoC(){Person p = ctx.GetObject("person") as Person; Console.WriteLine(p.pet.name);Console.WriteLine("-------------------------");}調(diào)用:
static IapplicationContext ctx = ContextRegistry.GetContext(); static void Main(string[] args) { fistIoC(); Console.ReadLine(); }
控制臺(tái)輸出:
旺財(cái)
-------------------------ok 第一個(gè)ioc例子就這樣結(jié)束了。簡(jiǎn)單的說(shuō):spring.net 就像是個(gè)實(shí)例化工廠,對(duì)實(shí)例對(duì)象注入,實(shí)例對(duì)象進(jìn)行屬性的賦值等。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注