本文将按B/S与C/S结构介绍Spring.Net的基本使用方法。
B/S结构下
1、配置web.config
<configuration>
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.WebContextHandler, Spring.Web"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
</sectionGroup>
</configSections>
<spring>
<context>
<resource uri="config://spring/objects"/>
</context>
<objects xmlns="http://www.springframework.net">
<!--
需要自行配置的部分
<object type="要注入属性.aspx页面">(注意是type,不是id)
<property name="公开的属性名称" ref="一个实体的id"/>
</object>
-->
<object type="Default.aspx">
<property name="Bean_user" ref="userBean"/>
</object>
<object id="userBean" type="Beans.UserBean, Beans" />
</objects>
</spring>
<httpHandlers>
<add verb="*" path="*.aspx" type="Spring.Web.Support.PageHandlerFactory, Spring.Web"/>
</httpHandlers>
<httpModules>
<add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web"/>
</httpModules>
</configuration>
2、aspx页面
public IUserBean Bean_user
{
get;
set;
}
3、接口
namespace IBeans
{
public interface IUserBean
{
string GetName();
}
}
4、实现类
namespace Beans
{
public class UserBean:IUserBean
{
#region IUserBean 成员
public string GetName()
{
return "张三";
}
#endregion
}
}
这样就可以直接在页面对bean进行调用,从而解除页面与业务类之间的紧密耦合。相对于工厂模式,他的耦合度更低,页面类与工厂对象的耦合也消失了,所有的改动都只在配置文件中完成。
C/S结构下
1、配置App.config
<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"/>
</context>
<objects xmlns="http://www.springframework.net">
<object id="userBean" type="Beans.UserBean, Beans" />
</objects>
</spring>
</configuration>
我们可以看到,与B/S结构的配置区别在于 <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
2、调用
IApplicationContext ac = ContextRegistry.GetContext();
IUserBean bean_user = ac["userBean"] as IUserBean;
Console.WriteLine(bean_user.GetName());
这就是Spring.Net的基本入门用法,快动手使用一下吧。
dll包下载地址:svn://www.irmcn.net/trunk/software/ASP.net/Spring.NET_2.0_dll.rar