承接上文
对象的各种实例化
.net篇(环境为vs2012+Spring.Core.dll)
修改原来的PersonDao对象为
public class PersonDao : IPersonDao{ public string name; private child chlid; public PersonDao(string Name){ this.name = Name; } public PersonDao(string Name,child Child){ this.name = Name; this.chlid = Child; } public void sayhello(){ Console.WriteLine(this.name); } public class child { } public IPersonDao CreateInstance(string name) { return new PersonDao(name); } public static IPersonDao factoryInstance(string name) { return new PersonDao(name); } }
修改原来的app.config对象为
<spring> <typeAliases> <alias name="PersonDaoAlias" type="SpringBase.PersonDao,SpringBase" /> </typeAliases> <context name="test"> <resource uri="config://spring/objects" /> <!--<resource uri="file://objects.xml" />--> </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" > <object name="child" type="SpringBase.PersonDao+child,SpringBase"></object> <object name="PersonDao" type="PersonDaoAlias" singleton="false"> <constructor-arg value="hello" index="0" /> <property name="name" value="aa"></property> </object> <object name="PersonchildDao" type="PersonDaoAlias" singleton="true" lazy-init="true"> <constructor-arg value="hello" index="0" /> <constructor-arg name="Child" ref="child" /> </object> <object name="staticfactoryDao" type="PersonDaoAlias" factory-method="factoryInstance"> <constructor-arg value="hello" index="0" /> </object> <object name="factoryDao" factory-method="CreateInstance" factory-object="PersonDao"> <constructor-arg value="hello" index="0" /> </object> </objects> </spring>
- 嵌套类型的对象实例化 在PersonDao中再添加一个类child(也就是内部类)
用+号表示内部类<object name="child" type="SpringBase.PersonDao+child,SpringBase"></object>
ContextRegistry.GetContext("test").GetObject("child")
- 当对象是一个泛型的时候
public class VarClass<T> { }
因为在xml文件里面<符号是敏感符号所以用html的<object name="var" type="SpringBase.VarClass<int>,SpringBase"></object>
<
来代替, 工厂模式创建泛型也就是把方法上的泛型进行赋予类型a() , 那么factory-method为a<int,int>
当泛型为内部类的时候,实例化失败,未知原因
java篇(环境为Maven+Jdk1.7+IntelliJ IDEA 12.1.4)
补充java的alias 当配置文件设置如下的时候, 在程序里面可以通过ctx.getBean("PersonDaoAlias");别名来实例化
<beans> <alias name="PersonDao" alias="PersonDaoAlias" /> <bean id="PersonDao" class="springdemo.