首页 > 代码库 > 构造函数注入
构造函数注入
namespace SpringNetZhuru
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person Friend { get; set; }
}
}
namespace SpringNetZhuru
{
public class PersonDao
{
private Person argPerson;
private int inPro;
public PersonDao(Person argperson, int inPro)
{
this.argPerson = argperson;//参数argperson为配置文件中构造器name使用
this.inPro = inPro;
}
public void get()
{
//构造函数注入的整行参数
Console.WriteLine(string.Format("intPro:{0}", this.inPro));
//构造函数注入的Person
Console.WriteLine(string.Format("Person的Name:{0}", this.argPerson.Name));
Console.WriteLine(string.Format("Person的age:{0}", this.argPerson.Age));
//构造函数的注入的Person的Friend
Console.WriteLine(String.Format("Person的Friend的Name:{0}", this.argPerson.Friend.Name));
Console.WriteLine(String.Format("Person的Friend的Age:{0}", this.argPerson.Friend.Age));
//构造函数 注入的Person的Friend的Friend
Console.WriteLine(String.Format("Person的Friend的Friend的Name:{0}", this.argPerson.Friend.Friend.Name));
Console.WriteLine(String.Format("Person的Friend的Friend的Age:{0}", this.argPerson.Friend.Friend.Age));
}
}
}
两个类:Person和PersonDao
构造函数注入和属性注入一样使用name,ref ,value
配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core" />
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
</configSections>
<spring>
<context>
<resource uri="config://spring/objects" />
</context>
<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">
<description>一个简单的控制反转例子</description>
<object id="computer" type="SpringNetZhuru.NowPeopleTool,SpringNetZhuru"></object>
<object id="nowpeople" type="SpringNetZhuru.NowPeople,SpringNetZhuru">
<property name="Tool" ref="computer"></property>
</object>
<object id="person" type="SpringNetZhuru.Person,SpringNetZhuru">
<property name="Name" value="http://www.mamicode.com/danche"></property>
<property name="Age" value="http://www.mamicode.com/24"></property>
<property name="Friend">
<object type="SpringNetZhuru.Person,SpringNetZhuru">
<property name="Name" value="http://www.mamicode.com/tanyidan"></property>
<property name="Age" value="http://www.mamicode.com/24"></property>
<property name="Friend" ref="person"></property>
</object>
</property>
</object>
//构造器注入
<object id="persondao" type="SpringNetZhuru.PersonDao,SpringNetZhuru">
<constructor-arg name="argperson" ref="person"></constructor-arg>//此处name为PersonDao构造函数的Person类型参数,而不是属性
<constructor-arg name="inPro" value="http://www.mamicode.com/1"></constructor-arg>//此处name为PersonDao构造函数的int 类型参数,而不是属性
</object>
</objects>
</spring>
</configuration>
运行结果: