bean元素配置:
scope:singleton(单例对象),prototype(多例),request,session。
singleton:被标识为单例对象在spring容器中只会存在一个实例
prototype:每次再获得才会创建,每次创建都是新的
package cn.itzy.b_create;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itzy.bean.User;
public class Dome{
@Test
public void fun1(){
//1.创建容器对象
ApplicationContext ac =new ClassPathXmlApplicationContext("cn/itzy/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 u4=(User) ac.getBean("User");
//四个对象返回同一个
System.out.println(u2==u4);
//3.打印User
System.out.println(u1);
System.out.println("holle world");
}
public void fun2(){
//1.创建容器对象
ApplicationContext ac =new ClassPathXmlApplicationContext("cn/itzy/b_create/applicationContext.xml");
//2.向容器要User对象
User u=(User) ac.getBean("User2");
//3.打印User
System.out.println(u);
}
public void fun3(){
//1.创建容器对象
ApplicationContext ac =new ClassPathXmlApplicationContext("cn/itzy/b_create/applicationContext.xml");
//2.向容器要User对象
User u=(User) ac.getBean("User3");
//3.打印User
System.out.println(u);
System.out.println("实例");
}
}
package cn.itzy.b_create;
public class User {
public User() {
//super();
System.out.println("空参user对象");
// TODO Auto-generated constructor stub
}
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
package cn.itzy.b_create;
import cn.itzy.bean.User;
public class UserFactory {
public static User createUser(){
System.out.println("静态工厂创建");
return new User();
}
public User createUser2(){
System.out.println("实例工厂");
return new User();
}
}
<?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 ">
<!-- 创建方式一:空参构造创建 -->
<bean name="User" class="cn.itzy.bean.User" scope= "singleton/prototype"></bean>
<!-- 创建方法二:创建静态工厂
调用UserFactory的createUser方法创建名为User2的对象,放入容器
-->
<bean name = "User2"
class="cn.itzy.b_create.UserFactory"
factory-method = "createUser"></bean>
<!-- 创建方法三:实例工厂 -->
<bean name="User3"
factory-bean = "UserFactory"
factory-method = "createUser2"
></bean>
<bean name = "UserFactory"
class = "cn.itzy.b_create.UserFactory"
></bean>
</beans>