1.分别新建Main和Web两个web工程
空工程并勾选上Mvc和WebApi
Main做为真正实现功能的工程
Web做为所有工程的入口
当然不只有一个Main工程,也会有其它工程
来共用一个Web做为入口
2.删除Main工程里的App_Data、App_Start、Global.asax
packages.config、Web.config(因为这些文件都依赖Web工程的)
两个工程同时删除View文件夹,因为是WebApi所以没有View
3.Web参照引用Main工程
4.通过NuGet分别为两个工程添加Spring.Net(一定要2.0以上版本)
安装一个Spring.Data.NHibernate4就把大多数库都导进来了
另外再安装一个Spring.Web.Mvc5
5.修改Web工程的Global基类为SpringMvcApplication并添加下面代码:
protectedvoid Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
protectedoverrideSystem.Web.Http.Dependencies.IDependencyResolverBuildWebApiDependencyResolver()
{
varresolver =base.BuildWebApiDependencyResolver();
varspringResolver = resolverasSpringWebApiDependencyResolver;
if(springResolver !=null)
{
//这里需要导入所有工程与spring相关的配置文件
//习惯把配置文件设置成埋入状态,因此是assembly://开关
springResolver.AddChildApplicationContextConfigurationLocation("assembly://Main/Main.Config/Index.xml");
}
returnresolver;
}
6.在Web工程的Web.config里添加:
<configuration>
//必须贴着configuration来写
<configSections>
<sectionGroupname="spring">
<sectionname="context"type="Spring.Context.Support.MvcContextHandler,Spring.Web.Mvc5"/>
</sectionGroup>
</configSections>
<spring>
<context>这里不能写东西!</context>
</spring>
7.在Main工程里创建Config文件夹,里面添加3个.xml文件并右键属性设置成埋入:
Controller.xml:
<?xml version="1.0" encoding="utf-8"?>
<objectsxmlns="http://www.springframework.net">
//type属性要根据Controller类的namespace来写,Service同样
<objectid="LoginController"type="Main.Login.LoginController,Main"singleton="false">
<propertyname="Service"ref="LoginService"></property>
</object>
</objects>
Service.xml:
<?xml version="1.0" encoding="utf-8"?>
<objectsxmlns="http://www.springframework.net">
<objectid="LoginService"type="Main.Login.Service.LoginService,Main"singleton="true"/>
</objects>
Index.xml:
<?xml version="1.0" encoding="utf-8"?>
<objectsxmlns="http://www.springframework.net">
<importresource="Service.xml"/>
<importresource="Controller.xml"/>
</objects>
8.在Main工程里创建LoginController和LoginService
namespaceMain.Login
{
publicclassLoginController :ApiController
{
//依赖注入进来的Service
publicLoginService Service {get;set; }
[HttpGet]
[Route("api/login/index")]
publicstringIndex()
{
returnService.test();
}
}
}
namespaceMain.Login.Service
{
publicclassLoginService
{
publicstringtest()
{
return"i am LoginService";
}
}
}
9.在Web工程的根目录下放一个Index.html和一个jquery文件
<!DOCTYPE html>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=utf-8"/>
<title></title>
<metacharset="utf-8" />
<scripttype="text/javascript"src="jquery-1.10.2.min.js"></script>
<scripttype="text/javascript">
$(function() {
$.ajax({ url:'api/login/index' })
.done(function (d, s) { alert(d); })
.fail(function (xr) { alert(xr.responseText); });
});
</script>
</head>
<body>
</body>
</html>
10.运行Web工程后得alert显示:i am LoginService