在Spring中,bean的作用范围分以下几种:
singleton:spring ioc容器中仅有一个bean实例,bean以单例的方式存在
prototype:每次从容器中调用bean时,都返回一个新的实例
request:每次http请求都会创建一个新的bean
session:同一个http session共享一个bean
global session:同一个全局session共享一个bean 一般用于portlet应用环境
application:同一个application共享一个bean
singleton
package com.fuwh.test; public class Dog { public int id;
public String name;
public int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Dog [id=" + id + ", name=" + name + ", age=" + age + "]";
} }
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="dog" class="com.fuwh.test.Dog" scope="singleton">
<property name="id" value="001"></property>
<property name="name" value="heihu"></property>
<property name="age" value="5"></property>
</bean> </beans>
package com.fuwh.test; import org.junit.Before;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { private ApplicationContext ac; @Before
public void setUp() throws Exception {
ac=new ClassPathXmlApplicationContext("beans.xml");
} @org.junit.Test
public void test() {
System.out.println(ac.getBean("dog")==ac.getBean("dog"));
}
}
返回结果 : true
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="dog" class="com.fuwh.test.Dog" scope="prototype">
<property name="id" value="001"></property>
<property name="name" value="heihu"></property>
<property name="age" value="5"></property>
</bean> </beans>
package com.fuwh.test; import org.junit.Before;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { private ApplicationContext ac; @Before
public void setUp() throws Exception {
ac=new ClassPathXmlApplicationContext("beans.xml");
} @org.junit.Test
public void test() {
System.out.println(ac.getBean("dog")==ac.getBean("dog"));
}
}
返回结果:false