Friday, 6 March 2009

C# Define and execute bean from the spring configuration file

Create spring configuration file spring.xml with a sample bean definition

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
  <object id="MyClass" type="MyCompany.MyClass,MyCompany" >
    <property name="name" value="John"/>
  </object>
</objects>

Use XmlApplicationContext to access bean

namespace MyCompany
{
    [TestFixture]
    public class Test
    {
        public void Test1()
        {            
            IApplicationContext context = new XmlApplicationContext("spring.xml");
            IObjectFactory factory = context;
            MyClass obj = (MyClass)factory["MyClass"];            
            obj.Test();
        }
    }
    public class MyClass
    {
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public void Test()
        {
            Console.WriteLine(string.Format("My name is {0}", name));
        }
    }
}

No comments:

Post a Comment