初入Spring.net

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

IOC:Inversion Of Control

控制翻转:就是创建对象的权利由开发人员自己控制,转换到了由容器来控制

我用的是winform里的一个按键来触发的

首先要引入两个SPRing.net的dll文件Common.Logging.dll 和Spring.Core.dll

privatevoidbutton1_Click(objectsender, EventArgs e)

{

IapplicationContext ctx=ContextRegistry.GetContext();

UserInfoService userInfo= (UserInfoService)ctx.GetObject("UserInfoService");

userInfo.Show();

}

publicclassUserInfoService

{publicUserInfo user {get;set; }

//构造函数publicUserInfoService(intage)

{

Age=age;

}publicintAge {get;set; }publicstringserverName {get;set; }publicvoidShow()

{

Console.WriteLine("OK2------"+serverName);

Console.WriteLine("Age="+Age);

Console.WriteLine("User="+user.uName);

}

}

}

//user类型

namespaceSpringDemo

{publicclassUserInfo

{publicstringuName {get;set; }

}

}

之后就直接在app.config里注入代码就可以了

<?xmlversion="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="config://spring/objects"/>

<resource uri="file://Servicess.xml"/>

</context>

<objects xmlns="http://www.springframework.net">

<description>An example that demonstrates simple IoC features.</description>

<objectname="UserInfoService"type="SpringDemo.UserInfoService, SpringDemo">

<constructor-arg name="age"value="18"/>//--------构造函数注入

<property name="serverName"value="yang"/>//------------属性注入

<property name="user"ref="UserInfo"/>

</object>

<objectname="UserInfo"type="SpringDemo.UserInfo, SpringDemo">//-----user类型的注入

<property name="uName"value="yang2"/>

</object>

</objects>

</spring>

</configuration>

然后调试就完美输出了

OK2---------yang

Age=18

User=yang2

从现在开始一点点进步

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航