本文源码地址:http://download.csdn.net/detail/xz2001/4944407
一、下载安装
目前Spring.NET的最新版是2.0,但正式版是1.3.2,官方下载地址:http://www.springsource.org/download/community?project=Spring.NET
本文之所以用2.0,是因为1.3.2不支持ASP.NET MVC4,最高支持ASP.NET MVC3。
下载后解压,需要用到这几个:Spring.Aop.dll、Spring.Data.dll、Spring.Core.dll、Spring.Data.NHibernate33.dll(适用于NHibernate3.3)和Spring.Web.Mvc4.dll。
把这四个文件也放到解决方案的Lib目录中,并为添加如下引用:
1、Dao项目中添加Spring.Data、Spring.Core、Spring.Data.NHibernate33引用;
2、Web项目中,这五个dll全部加进去。
现在既然要把Spring.NET整合进来,自然要使用Spring的强大功能--Ioc。现在就一步一步编写每一层的代码,并在控制器中使用。
二、编写数据访问层接口
在IDao项目中创建接口:IUserDao,内容如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using LMJ.Model; namespace LMJ.IDao { public interface IUserDao { User readByCode(String code); } }
在Dao项目中创建类:UserDao,内容如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Spring.Data.NHibernate.Generic.Support; using Spring.Data.NHibernate.Generic; using LMJ.IDao; using LMJ.Model; namespace LMJ.Dao { public class UserDao : HibernateDaoSupport, IUserDao { public User readByCode(String code) { return HibernateTemplate.Get<User>(code); } } }
四、编写业务逻辑层接口
在IUserService项目中创建接口:IUserService,内容如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using LMJ.Model; namespace LMJ.IService { public interface IUserService { User readByCode(String code); } }
在UserService项目中创建类:UserService,内容如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using LMJ.IDao; using LMJ.Model; using LMJ.IService; namespace LMJ.Service { public class UserService : IUserService { public IUserDao UserDao { get; set; } public User readByCode(String code) { return UserDao.readByCode(code); } } }
六、配置log4net日志组件
程序员的必备工具:log4net,在NHibernate、Spring.NET中都有这个dll,共需要2个:log4net.dll、Common.Logging.dll。复制到Lib目录后,在使用的层中引入进来,这里为了测试方便,直接在Web项目中引用。
然后是创建个配置文件、修改AssemblyInfo.cs就可以用了,具体操作看这里:http://blog.csdn.net/xz2001/article/details/8450548
七、修改UserController代码,修改后的内容如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Collections; using LMJ.IService; using Spring.Data; namespace LMJ.Web.Areas.Manage.Controllers { public class UserController : Controller { private log4net.ILog log = log4net.LogManager.GetLogger(typeof(UserController)); public IUserService UserService { get; set; } public String Message { get; set; } public ActionResult Index() { log.Info("注入值:" + Message); ViewBag.Message = Message; return View(); } public ActionResult Test() { log.Info("注入值:" + Message); NHibernate.ISessionFactory sessionFactory = new NHibernate.Cfg.Configuration().Configure().BuildSessionFactory(); NHibernate.ISession session = sessionFactory.OpenSession(); if (session != null) { IList results = session.CreateQuery("from User").List(); this.Message += ",数据总数:" + results.Count; session.Close(); } ViewBag.Message = Message; return View("Index"); } public ActionResult Read() { log.Info("注入值:" + Message); try { LMJ.Model.User user = UserService.readByCode("101"); this.Message += ",名称:" + user.Name; } catch (Exception ex) { this.Message += "" + ex.ToString(); log.Error(ex.ToString()); } ViewBag.Message = Message; return View("Index"); } } }
八、创建配置文件
在Web项目根目录下创建SpringHibernate.xml,注意下文件名,在Web.config中会使用这个文件,内容如下:
方法一:
<?xml version="1.0" encoding="utf-8" ?> <objects xmlns="http://www.springframework.net" xmlns:tx="http://www.springframework.net/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:db="http://www.springframework.net/database"> <db:provider id="DbProvider" provider="MySql-5.2.3" connectionString="Database=lmj;Data Source=localhost;User Id=root;Password=root"/> <object id="NHibernateSessionFactory" type="Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate33"> <property name="DbProvider" ref="DbProvider"/> <property name="MappingAssemblies"> <list> <value>LMJ.Model</value> </list> </property> <property name="HibernateProperties"> <dictionary> <entry key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" /> <entry key="connection.driver_class" value="NHibernate.Driver.MySqlDataDriver" /> <entry key="dialect" value="NHibernate.Dialect.MySQL5Dialect" /> <entry key="show_sql" value="true" /> <entry key="hbm2ddl.keywords" value="none" /> <entry key="query.substitutions" value="true 1, false 0, yes 'Y', no 'N'" /> </dictionary> </property> </object> <object id="HibernateTransactionManager" type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate33"> <property name="DbProvider" ref="DbProvider"/> <property name="SessionFactory" ref="NHibernateSessionFactory"/> </object> <object id="HibernateTemplate" type="Spring.Data.NHibernate.HibernateTemplate"> <property name="SessionFactory" ref="NHibernateSessionFactory" /> <property name="TemplateFlushMode" value="Auto" /> <property name="CacheQueries" value="true" /> </object> <object id="UserDao" type="LMJ.Dao.UserDao"> <property name="SessionFactory" ref="NHibernateSessionFactory" /> </object> <object id="UserService" type="LMJ.Service.UserService"> <property name="UserDao" ref="UserDao" /> </object> </objects>
这里需要注意个问题,就是访问MySQL Mysql.Data.dll的版本问题,我这里配置的provider的参数是“MySql-5.2.3”,打开Spring.NET下载包中的"\src\Spring\Spring.Data\Data\Common\dbproviders.xml"文件,就明白了。
另外,也要向Web.config中添加一些配置,如下内容:
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <sectionGroup name="spring"> <section name="context" type="Spring.Context.Support.MvcContextHandler, Spring.Web.Mvc4"/> <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" /> <section name="parsers" type="Spring.Context.Support.NamespaceParsersSectionHandler, Spring.Core" /> </sectionGroup> </configSections> <spring> <parsers> <parser type="Spring.Data.Config.DatabaseNamespaceParser, Spring.Data"/> <parser type="Spring.Transaction.Config.TxNamespaceParser, Spring.Data" /> </parsers> <context> <resource uri="file://~/SpringHibernate.xml"/> <resource uri="file://~/Config/Controller.xml"/> </context> </spring> ...... </configuration>
方法二:
把数据库访问信息放到Web.config中,这样更安全一些,SpringHibernate.xml的内容是这样的:
<?xml version="1.0" encoding="utf-8" ?> <objects xmlns="http://www.springframework.net" xmlns:tx="http://www.springframework.net/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:db="http://www.springframework.net/database"> <object type="Spring.Objects.Factory.Config.PropertyPlaceholderConfigurer, Spring.Core"> <property name="ConfigSections" value="databaseSettings" /> </object> <db:provider id="DbProvider" provider="MySql-5.2.3" connectionString="Data Source=${db.datasource};Database=${db.database};User Id=${db.user};Password=${db.password};"/> <object id="NHibernateSessionFactory" type="Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate33"> <property name="DbProvider" ref="DbProvider"/> <property name="MappingAssemblies"> <list> <value>LMJ.Model</value> </list> </property> <property name="HibernateProperties"> <dictionary> <entry key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" /> <entry key="connection.driver_class" value="NHibernate.Driver.MySqlDataDriver" /> <entry key="dialect" value="NHibernate.Dialect.MySQL5Dialect" /> <entry key="show_sql" value="true" /> <entry key="hbm2ddl.keywords" value="none" /> <entry key="query.substitutions" value="true 1, false 0, yes 'Y', no 'N'" /> </dictionary> </property> </object> <object id="HibernateTransactionManager" type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate33"> <property name="DbProvider" ref="DbProvider"/> <property name="SessionFactory" ref="NHibernateSessionFactory"/> </object> <object id="HibernateTemplate" type="Spring.Data.NHibernate.HibernateTemplate"> <property name="SessionFactory" ref="NHibernateSessionFactory" /> <property name="TemplateFlushMode" value="Auto" /> <property name="CacheQueries" value="true" /> </object> <object id="UserDao" type="LMJ.Dao.UserDao"> <property name="SessionFactory" ref="NHibernateSessionFactory" /> </object> <object id="UserService" type="LMJ.Service.UserService"> <property name="UserDao" ref="UserDao" /> </object> </objects>
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <sectionGroup name="spring"> <section name="context" type="Spring.Context.Support.MvcContextHandler, Spring.Web.Mvc4"/> <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" /> <section name="parsers" type="Spring.Context.Support.NamespaceParsersSectionHandler, Spring.Core" /> </sectionGroup> <section name="databaseSettings" type="System.Configuration.NameValueSectionHandler"/> </configSections> <databaseSettings> <add key="db.datasource" value="localhost" /> <add key="db.database" value="lmj" /> <add key="db.user" value="root" /> <add key="db.password" value="root" /> </databaseSettings> <spring> <parsers> <parser type="Spring.Data.Config.DatabaseNamespaceParser, Spring.Data"/> <parser type="Spring.Transaction.Config.TxNamespaceParser, Spring.Data" /> </parsers> <context> <resource uri="file://~/SpringHibernate.xml"/> <resource uri="file://~/Config/Controller.xml"/> </context> </spring> ...... </configuration>
从配置文件中可以看出,还少个配置文件:Web项目中的:Config/Controller.xml,内容如下:
<?xml version="1.0" encoding="utf-8" ?> <objects xmlns="http://www.springframework.net"> <object type="LMJ.Web.Areas.Manage.Controllers.UserController,LMJ.Web" singleton="false" > <property name="Message" value="Hello World" /> <property name="UserService" ref="UserService" /> </object> </objects>
九、修改Global继承类
差点忘记了,打开Global类,修改成从Spring.Web.Mvc.SpringMvcApplication继承,这时将由Spring管理系统。
现在终于完成了,可以测试了。打开浏览器,根据你项目的实际情况输入地址,我的是这样的:http://localhost:1001/Manage/User/Index,访问另外二个Action,看下结果。
写东西真累,今天不写了,自己研究代码,下一篇开始整合ExtJS4.0。
文章写的都是最基本的东西,想放在项目中使用,还有诸多问题需要解决,这里仅能帮助那些和我一样学习的朋友,希望对你们有所帮忙。
老规矩,源码地址:http://download.csdn.net/detail/xz2001/4944407