Spring是Java世界里的著名框架,它简化了J2EE开发中的许多过程,.Net环境自然也需要诸如IoC,AOP之类的功能。
首先我们创建一个Asp.Net空Web应用程序,名称叫MemoBoxServer,传统的WebService开发是创建一个继承自System.Web.Services.WebService的类,并加上一系列Attribute实现。
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
这样虽然简单,但是对实现WebService的类本身来说,显得过于臃肿,也不便于将来与框架分离。
下面我们用Spring.Net来实现这个Hello World
推荐使用NuGet进行引用管理,搜索Spring,我们添加以下包:
Spring.Core
Spring.Aop
Spring.Data
Spring.Web
Spring.Net NHibernate 3.2 Support
准备工作完成,下面进入正题,Spring.Net中的WebService怎么实现?很简单,把上面那个类的Attribute和继承去掉,并为对外服务抽象接口:
public class WebService1 : IWebService1
{
public string HelloWorld()
{
return "Hello World";
}
}
public interface IWebService1
{
string HelloWorld();
}
但是现在我们还不能访问它,现在我们需要让Spring.Net接管我们的请求,为我们提供服务,修改Web.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>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" type="Spring.Web.Services.WebServiceHandlerFactory, Spring.Web"/>
</httpHandlers>
</system.web>
<spring>
<context>
<resource uri="config://spring/objects"/>
</context>
<objects xmlns="http://www.springframework.net" xmlns:aop="http://www.springframework.net/aop">
<object id="MemoBoxServer.WebService1"
type="MemoBoxServer.WebService1, MemoBoxServer"
scope="request">
</object>
<object id="WebService1" type="Spring.Web.Services.WebServiceExporter, Spring.Web">
<property name="TargetName" value="MemoBoxServer.WebService1"/>
<property name="Namespace" value="http://tempuri.org/"/>
<property name="Description" value="Hello World"/>
<property name="MemberAttributes">
<dictionary>
<entry key="*">
<object type="System.Web.Services.WebMethodAttribute, System.Web.Services">
</object>
</entry>
</dictionary>
</property>
</object>
</objects>
</spring>
</configuration>
下面运行试试,根据配置,我们让Spring接管了以asmx结尾的请求,我们访问
localhost:45984/WebService1.asmx,如果看到以下页面就说明成功了
点击HelloWorld并调用,将得到如下返回:
<string xmlns="http://tempuri.org/">Hello World</string>
至此,我们已经初步了解了如何用Spring.Net来开发WebService应用,下一节将讲解如何进行分层设计