Bean的实例化
-
构造器实例化(最常用)
-
静态工厂方式实例化
-
实例工厂方式实例化
构造器实例化(最常用)
public class Bean1 {
}
public class InstanceTest1 {
public static void main(String[] args) {
String xmlPath = "com/itheima/instance/constructor/bean1.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
Bean1 bean = (Bean1) applicationContext.getBean("bean1");
System.out.println(bean);
}
}
public class Bean2 {
}
public class MyBean2Factory {
public static Bean2 createBean(){
return new Bean2();
}
}
public class InstanceTest2 {
public static void main(String[] args) {
String xmlPath = "com/itheima/instance/static_factory/bean2.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
Bean2 bean = (Bean2) applicationContext.getBean("bean2");
System.out.println(bean);
}
}
实例工厂方式实例化
public class Bean3 {
}
public class MyBean3Factory {
public MyBean3Factory(){
System.out.println("bean3工厂实例化中");
}
public Bean3 createBean(){
return new Bean3();
}
}
public class InstanceTest3 {
public static void main(String[] args) {
String xmlPath = "com/itheima/instance/factory/bean3.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
Bean3 bean = (Bean3) applicationContext.getBean("bean3");
System.out.println(bean);
}
}