Spring.Net 初探

时间:2023-03-09 06:19:45
Spring.Net 初探

Spring.Net 初探之牛刀小试

又是一个周末,感受着外面30°的高温,果断宅在家里,闲来无事,就研究了一下spring .net 框架, 在这里不得不说 vs2013确实是一个强大的开发工具(起码对于.net开发来说是这样的),哈哈 废话不多说了开始展示一下我的成果吧.

1、  项目采用多层架构 IRepository/Repository/Service/Web层,而spring.net主要安装在service层,这样做的目的就是使注入和web层分开,使代码逻辑更加清晰,而在web层只需根据service层的类进行静态调用即可。项目架构如图所示:

Spring.Net 初探

在此之前需要在webconfig中配置spring.xml目录,代码如下所示:

Spring.Net 初探
1   <!--Spring.Net节点详细配置-->
2 <spring>
3 <context>
4 <!--读取嵌入在程序集中的配置文件-->
5 <!--<resource uri="file://~/Config/Spring.xml"/>-->
6 <!--读取嵌入在程序集中的配置文件 将Spring.xml的属性设置为【嵌入的资源】-->
7 <resource uri="assembly://Spring.Net.Service/Spring.Net.Service.Config/Spring.xml"/>
8 </context>
9 </spring>
Spring.Net 初探

下面就以BookInfo类为例贴出代码

1、IBookInfo接口类定义代码,定义函数

2、BookInfo实现类代码

3、BookService逻辑处理类代码,在该类中用到了依赖注入技术,将BookInfo注入到Service中,需在Spring.xml中进行配置

4、spring.xml配置代码

5、web层调用

Spring.Net 初探
1         public ActionResult SpringTest()
2 {
3 //ViewBag.Msg = UserRegInfoService.GetAllData();
4 //ViewBag.Msg = LoginService.LoginInfo();
5 ViewBag.Msg = BookInfoService.GetBook();
6 return View();
7 }
Spring.Net 初探

6、效果图如下所示:

Spring.Net 初探

在spring.xml中 有几点需要注意:

1、当object属性中的singleton为true时,标识已单例模式访问service类,故函数要写为静态的,如BookService代码所示,否则运行不正常。

2、object和property的name属性值 必须和service类代码里约定的一致,例如:在BookService里约定 对象为static IBookInfo Book { get; set; },那么在<property name="Book" ref="Book" />就必须保持一致,否则运行不正常。

3、spring.xml文件【生成操作属性】要设置为嵌入的资源,否则,配置文件报错。

以上就是本人对spring.net的浅析,如有需更正的地方,请各位多多指点,期待与热爱技术的你共同进步。