首页 > 代码库 > spring.net框架配置和使用

spring.net框架配置和使用

            spring.net框架学习笔记

spring.net框架是用于解决企业应用开发的复杂性的一种容器框架,它的一大功能IOC(控制反转),通俗解释就是通过spring.net框架的容器创建对象实体,而不是通过程序员new出来。只要在spring.net的相应xml中配置节点,在获取对象的时候就可以通过 

IApplicationContext ctx = ContextRegistry.GetContext();

UserInfoDal dal = ctx.GetObject("UserInfoDal") as UserInfoDal;

来创建实体对象,这样就可以在XML里通过配置修改或者替换UserInfoDal类,降低程序对服务类的依赖性,符合软件设计中的OCP(开闭原则),提高软件的可扩展性。IOC也叫DI(依赖注入),这两种不同的叫法可以这样理解,在应用程序整体中理解为控制反转(控制权交由应用程序),在容器对对象实例化的角度叫做DI(依赖对象通过xml配置文件让外部容器将其注入到程序中)。

1.引用相应dll文件Common.Logging.dll和Spring.Core.dll

2.使用Spring.net需要配置应用程序的配置文件:

 1 <?xml version="1.0" encoding="utf-8" ?> 2 <configuration> 3  4   <configSections> 5  6     <!--Spring配置节点--> 7     <sectionGroup name="spring"> 8       <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/> 9       <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />10     </sectionGroup>11     <!--Spring配置节点结束-->12 13   </configSections>14 15 16   <!--Spring配置节点-->17   <spring>18 19     <context>20       <!--选择XML文件的位置,3种方式,1 配置文件 2 定位文件 3 程序集-->21       <resource uri="config://spring/objects"/>22       <!-- <resource uri="file://objects.xml"/>-->23       <!--<resource uri="assembly://SpringNetTest/SpringNetTest/objects1.xml"/>-->24     </context>25     <objects xmlns="http://www.springframework.net">26 27       <!--此处配置各种要注入的实体对象-->28       <object name="OrderInfo" type="SpringNetTest.OrderInfo,SpringNetTest">29         <property name="Id" value="1"/>30         <property name="Good" value="食品"/>31       </object>32       <!--autowire="constructor"根据构造函数注入 au-->33       <object name="UserInfoDal" type="SpringNetTest.UserInfoDal,SpringNetTest" autowire="byType">34         <constructor-arg name="Id" value="2"/>35         <!--<constructor-arg name="OrderInfo" ref="OrderInfo"/>-->36       </object>37       <object name="UserInfo" type="SpringNetTest.UserInfo,SpringNetTest">38         <property name="Id" value="1"/>39         <property name="Name" value="jayjay"/>40         <property name="OrderInfo" ref="OrderInfo"/>41       </object>42     </objects>43 44   </spring>45   <!--Spring配置节点结束-->46 47 </configuration>
ps:<object name="对象名" type="命名空间名称.类名,程序集名">

3.通过

IApplicationContext ctx = ContextRegistry.GetContext();

UserInfoDal dal = ctx.GetObject("UserInfoDal") as UserInfoDal;

创建容器上下文对象,接着创建服务类实体对象,对象即可与手动new出来一样正常使用。

spring.net框架配置和使用