在Spring中有三个实例化bean的方式:
1.使用构造器实例化
2.使用静态工厂方法实例化
3.使用实例化工厂方法实例化
(使用最普遍的是第一种,使用构造器实例化)
(1)使用构造器实例化
这种方法我们使用的最多,因为不再用去创建工厂类.最简单
测试类:
public class InstanceTest1 {
public static void main(String[] args) {
String xmlPath = "com/itheima/instance/constructor/beans1.xml";
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext(xmlPath);
Bean1 bean = (Bean1) applicationContext.getBean("bean1");
System.out.println(bean);
}
}
在xml中配置也是很简单
<bean id="bean1" class="com.itheima.instance.constructor.Bean1" />
(2)使用静态工厂方法实例化
想要使用此种实例化方法必需要有工厂类,而且工厂里要有静态方法
测试类:
public class InstanceTest2 {
public static void main(String[] args) {
String xmlPath ="com/itheima/instance/static_factory/beans2.xml";
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext(xmlPath);
System.out.println(applicationContext.getBean("bean2"));
}
}
静态工厂:
public class MyBean2Factory {
public static Bean2 createBean(){
return new Bean2();
}
}
xml:
<bean id="bean2" class="com.itheima.instance.constructor.MyBean2Factory" factory-method="createBean"/>
此种方法的xml和第一种有区别,需注意.
id是实例化对象的名称,class里面写工厂类,而factory-method是实现实例化类的静态方法
(3)使用实例化工厂方法实例化:
测试类:
public class InstanceTest3 {
public static void main(String[] args) {
String xmlPath = "applicationContext.xml";
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext(xmlPath);
System.out.println(applicationContext.getBean("bean3"));
}
}
工厂类:
public class MyBean3Factory {
public Bean3 createBean(){
return new Bean3();
}
}
xml:
<bean id="myBean3Factory" class="com.itheima.instance.constructor.MyBean3Factory"/>
<bean id="bean3" factory-bean="myBean3Factory" factory-method="createBean" />
此种方法需要注意,由于使用的是实例化工厂方法实例化,想要创建bean对象必须,得调用工厂方法,然后想要调用方法还必须要有工厂的对象,所以需要给工厂也写个bean标签.其中factory-bean对应被实例化工厂类的对象的名称,factory-method是工厂的非静态方法.