-
id 和 name
– id和name实际上配置的是bean的别名。
– id属性在IOC容器中必须唯一,而name一般来说也应该是唯一的。
– name的属性值可以包含特殊字符,id的属性值则不可以。除此外id和name基本是一样的。 -
class
– 用户设置一个类的完全路径,用于IOC容器生成类的实例。 -
scope
– Spring创建对象是单例还是多例取决于Bean的作用域。
Bean的作用域
类别 | 说明 |
---|---|
singleton (默认情况) | 在SpringIOC容器中仅存在一个Bean实例,Bean以单例的方式存在 |
prototype | 每次调用getBean()时都会返回一个新的实例 |
request | 每次HTTP请求都会创建一个新的Bean,作用域仅适用于WebApplicationConntext |
session | 同一个HTTP Session共享一个Bean,不同的HTTP Session 使用不同的Bean。改作用域仅适用于WebApplicationContext环境 |
Person类
package demo4;
public class Person {
Person(){
System.out.println("Person");
}
}
TestPerson类
package demo4;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestPerson {
@Test
public void test1(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Person p1 = (Person) applicationContext.getBean("person");
Person p2 = (Person) applicationContext.getBean("person");
System.out.println(p1.hashCode());
System.out.println(p2.hashCode());
}
}
applicationContext.xml配置文件:默认情况
<?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="person" class="demo4.Person"></bean>
</beans>
输出结果:单例
applicationContext.xml配置文件:scope="singleton"
<?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="person" class="demo4.Person" scope="singleton"></bean>
</beans>
输出结果:单例
applicationContext.xml配置文件:scope="prototype"
<?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="person" class="demo4.Person" scope="prototype"></bean>
</beans>
输出结果:多例
综上所述:Bean的作用域范围默认和singleton的情况下返回的是单例,prototype返回的是多例。