用户工厂类,UserFactory
public class UserFactory {
public static User createUser(){
System.out.println("静态工厂创建User");
return new User();
}
public User createUser2(){
System.out.println("实例工厂创建User");
return new User();
}
}
创建容器对象的方法:
public class Demo {
@Test
//创建方式1,空参构造
public void fun1(){
//1创建容器对象
ApplicationContext ac=new ClassPathXmlApplicationContext("cn/itheima/b_create/applicationContext.xml");
//2向容器要User对象
User u = (User) ac.getBean("user");
//打印user对象
System.out.println(u);
}
@Test
//创建方式2,静态工厂
public void fun2(){
//1创建容器对象
ApplicationContext ac=new ClassPathXmlApplicationContext("cn/itheima/b_create/applicationContext.xml");
//2向容器要User对象
User u = (User) ac.getBean("user2");
//打印user对象
System.out.println(u);
}
@Test
//创建方式3,动态工厂
public void fun3(){
//1创建容器对象
ApplicationContext ac=new ClassPathXmlApplicationContext("cn/itheima/b_create/applicationContext.xml");
//2向容器要User对象
User u = (User) ac.getBean("user3");
//打印user对象
System.out.println(u);
}
@Test
//scope:singleton单例
//scope:prototype多例
public void fun4(){
//1创建容器对象
ApplicationContext ac=new ClassPathXmlApplicationContext("cn/itheima/b_create/applicationContext.xml");
//2向容器要User对象
User u1 = (User) ac.getBean("user");
User u2 = (User) ac.getBean("user");
User u3 = (User) ac.getBean("user");
//打印user对象
//System.out.println(u);
System.out.println(u1==u3);
}
@Test
//测试生命周期方法
public void fun5(){
//1创建容器对象
ClassPathXmlApplicationContext ac=new ClassPathXmlApplicationContext("cn/itheima/b_create/applicationContext.xml");
//2向容器要User对象
User u = (User) ac.getBean("user");
//打印user对象
System.out.println(u);
//关闭容器,触发销毁方法
ac.close();
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
<!-- 创建方式1:空参构造 -->
<!-- scope属性:singleton单例,prototype:多例 -->
<bean name="user" class="cn.itheima.bean.User" init-method="init" destroy-method="destory"></bean>
<!-- 创建方式2:静态工厂
调用UserFactory的createUser方法创建名为user2的对象,放入容器
-->
<bean name="user2" class="cn.itheima.b_create.UserFactory"
factory-method="createUser"></bean>
<!-- 创建方式2:实例工厂
调用UserFactory的createUser2方法创建名为user3的对象,放入容器
-->
<bean name="user3"
factory-bean="UserFactory"
factory-method="createUser2"
></bean>
<bean name="UserFactory"
class="cn.itheima.b_create.UserFactory"
></bean>
</beans>