SPRING.NET 配置对象属性注入的例子

有几年没用spring.net了,下星期打算在项目里面用一下,毕竟注入能力太强大了。
首先还是用NuGet引用一下 Install-Package Spring.Core
下面创建三个类,其中一个类包含另外两个类作为属性

namespace SpringNetPropertyInject
{
    public class GameChannel
    {
        public string ChannelName { set; get; }
        public string ChannelId { set; get; }
    }
}

namespace SpringNetPropertyInject
{
    public class ChannelAccount
    {
        public string AccountName { set; get; }
        public string AccountId { set; get; }
    }
}

namespace SpringNetPropertyInject
{
    public class Test
    {
        public GameChannel Channel { set; get; }
        public ChannelAccount Account { set; get; }

        public void ShowName()
        {
            MessageBox.Show(Channel.ChannelName + Account.AccountName);
        }
    }
}

我不太喜欢在app.config文件里面配置东西,因为会把那个文件搞得很臃肿,下面用object.xml文件进行配置

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
  <object id="GameChannel" type="SpringNetPropertyInject.GameChannel">
    <property name="ChannelName" value="某某渠道"/>
  </object>
  <object id="ChannelAccount" type="SpringNetPropertyInject.ChannelAccount">
    <property name="AccountName" value="某某账户"/>
  </object>
  <object id="Test" type="SpringNetPropertyInject.Test">
    <property name="Channel" ref="GameChannel"/>
    <property name="Account" ref="ChannelAccount"/>
  </object>
</objects>

值得注意的是这两句

    <property name="Channel" ref="GameChannel"/>
    <property name="Account" ref="ChannelAccount"/>

Channel 为Test类里面的属性名称,它的注入配置节叫GameChannel,也就是下面这个

  <object id="GameChannel" type="SpringNetPropertyInject.GameChannel">
    <property name="ChannelName" value="某某渠道"/>
  </object>

这样把对象属性的属性也注入了,接着在程序中调用

using System;
using System.Windows.Forms;
using Spring.Context.Support;

namespace SpringNetPropertyInject
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var context
                = new XmlApplicationContext(Application.StartupPath + @"\object.xml");
            var test = context.GetObject("Test") as Test;
            if (test != null) 
                test.ShowName();
        }
    }
}

运行效果
可以看到,对象已被成功注入了

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值