您的位置:首页 > 编程语言 > Java开发

Spring.NET学习实践(2) ---修改下我们的小例子

2007-08-12 09:44 453 查看
来源:
http://blog.csdn.net/trisaeyes/archive/2006/12/27/1464727.aspx

在上一篇文章的最后,我们作了一个简单的例子,来使用Spring.NET,虽然这个例子真的是很简陋.

1 static void Main(string[] args)
2 {
3
4 StaticApplicationContext context = new StaticApplicationContext();
5 context.RegisterPrototype("HelloWorld", typeof(HelloWorld), null);
6
7 SayHi o = context.GetObject("HelloWorld") as SayHi;
8
9 System.Windows.Forms.MessageBox.Show(o.SayHello());
10 }

现在我们来看看这个例子的流程。

1.申请容器
StaticApplicationContext context = new StaticApplicationContext();
2.注册服务
context.RegisterPrototype("HelloWorld", typeof(HelloWorld), null);
3.获得服务组件
SayHi o = context.GetObject("HelloWorld") as SayHi;
4.使用组件
System.Windows.Forms.MessageBox.Show(o.SayHello());

麻雀虽小五脏俱全,或许我们以后要面对要复杂的多Spring.NET代码,但是基本上会和
上面这个例子走类似的流程。

但是这个例子也不是很完美。因为我们在第二步注册服务时,使用的是代码配置的方式,如果我们象更换服务组件时,我们不得不来修改代码,是我们无法忍受的,简直回到原始时代了(关于代码配置还是配置文件配置的问题,Spring社区和其他构架社区一样配置文件配置的声音占了绝大多数,但是平心而论代码配置还是尤其擅长的地方的,至少不想一些人说的那么让人忍受不了,甚至是一无是处)。

现在我们换个方式,使用常见的XML配置方式来修改下我们的小例子。
首先修改我们的配置文件(web.config或是App.config)
修改为以下的样式

<?xmlversion="1.0"encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroupname="spring">
<sectionname="context"type="Spring.Context.Support.ContextHandler, Spring.Core"/>
<sectionname="objects"type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
</configSections>

<spring>
<context>
<resourceuri="config://spring/objects"/>
</context>
<objectsxmlns="http://www.springframework.net">
<objectid="HelloWorld"type="TestSpringNetTestHelloWorld.HelloWorld, SpringTest" >
</object>
</objects>

</spring>

</configuration>

很简单把,<objectid="HelloWorld"type="TestSpringNetTestHelloWorld.HelloWorld, SpringTest" >
声明了一个HelloWorld的服务的组件配置
其中type是实现服务的组件
type="TestSpringNetTestHelloWorld.HelloWorld指明实现服务的组件类,
逗号后的SpringTest是组件所在的模块

代码中我们只需要修改注册方式即可。

IApplicationContext context = ContextRegistry.GetContext();
运行下,OK.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: