创建对象的三种方法
1.构造器创建
Spring默认调用类的“无参构造方法”来创建对象。上一篇使用的就是构造器创建
appContext.getBean(Class/"id");
2.静态工厂实现
静态工厂不需要实例化工厂
创建类
public class StaticFactory {
public StaticFactory() {
System.out.println("构造方法" + this.getClass());
}
public static Cat createObj() {
System.out.println("Cat creatObj()");
return new Cat();
}
}
配置文件,只写了bean
<!--静态工厂方法 -->
<bean id="id_staticFactory" class="club.laobainb1314.p02.StaticFactory" factory-method="createObj" />
Test
@Test
void test2() {
ApplicationContext appc = new ClassPathXmlApplicationContext(XML);
Cat c = (Cat) appc.getBean("id_staticFactory");
c.speak();
}
该工厂中有一个静态方法,该静态方法返回一个 Cat 的实例,不过这种方法并不常用
3.实例工厂实现
实例工厂就是普通的工厂,需要创建工厂对象。
public class Factory {
public Factory() {
System.out.println("构造方法:" + this.getClass());
}
public Cat createObj() {
System.out.println("createObj()");
return new Cat();
}
}
静态工厂一个bean,实例工厂至少需要两个bean,需要工厂bean,指定工厂可以有多个bean。
<!-- 实例工厂方法 -->
<!-- 工厂bean -->
<bean id="id_Foxconn" class="club.laobainb1314.p02.Factory"/>
<!-- 指定工厂和方法 -->
<bean id="id_getObj" factory-bean="id_Foxconn" factory-method="createObj" />
测试
@Test
void test3() {
ApplicationContext appc = new ClassPathXmlApplicationContext(XML);
Cat c = (Cat) appc.getBean("id_getObj");
c.speak();
}
多配置
一个项目可以有多克配置文件,使用import导入
<!-- 把类定义移到别的XML中,此处导入,和自己定义一样 -->
<import resource="/Contex.xml"/>
别名
<bean id="id_Iphone" factory-bean="id_Foxconn" factory-method="iphonex" />
<!-- 设置别名获取 -->
<alias name="id_Iphone" alias="iphone"/>
<bean id="id_MiIphone" factory-bean="id_Foxconn" factory-method="iphone4s" />
<alias name="id_MiIphone" alias="phone"/>
@Test
void test04() {
ApplicationContext appc = new ClassPathXmlApplicationContext(XML);
Car c = (Car)appc.getBean("id_LeSEE");
System.out.println(c);
c.le();
//通过别名获取
Iphone i = (Iphone)appc.getBean("iphone");
System.out.println(i);
MiPhone m = (MiPhone)appc.getBean("phone");
System.out.println(m);
}