Spring.net 学习IOC------属性注入

我们就完成我们的第一个spring.net学习IOC的“hello world!”。

1> 我们新建一个C# 的控制台项目名为Spring,然后引入Spring.Core.dll与日志库

2> 新建一个xml文件object.xml 内容如下:

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd">
  <object id="test" type="Spring.HelloWorld, Spring">
    <property name="name"  value="Hello World"/>
  </object>
</objects>

    当然我们也可以写在程序的配置文件中,但是我不喜欢写在配置文件中,而是重新创建一个xml文件。

3> 看我们的main方法中的内容:

#region 属性注入
           
            string path = System.AppDomain.CurrentDomain.BaseDirectory + "Object.xml";
             //1.引用spring.net 库
             //2.构造IOC 容器  
            IApplicationContext ctx = new XmlApplicationContext(path);
           
             //3.在IOC容器中获取实例
            HelloWorld he = ctx.GetObject("test") as HelloWorld;
            
            
             //4.调用hello方法
            //he.Hello();
            Console.WriteLine(he.name);
         
#endregion

4> 我们还需要定义一个HelloWorld的类

 class HelloWorld
    {
        public string name { get; set; }  //属性定义
    }

5> 说明

通过构造器创建对象需要满足:指明对象类型type="类全名,程序集名"(<object id="test" type="Spring.HelloWord, Spring" />),其中的id我们可以任意起名字。配置文件的结点必须是object。IApplicationContext 是一IOC容器的接口。属性注入时,我们需要在xml文件中的<object>结点下使用<property>结点。

 

代码下载

转载于:https://www.cnblogs.com/JeremyLuBlog/p/6268795.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值