什么是单例、多例:
单例就是所有的请求都用一个对象来处理,比如我们常用的service和dao层的对象通常都是单例的;
多例则指每个请求用一个新的对象来处理,比如action;
详细说明可参考: https://www.cnblogs.com/ggds/p/7855824.html
可以用Spring配置文件bean标签里面的scope属性, 来设置单实例/多实例.
Spring默认单实例, 即scope=singleton
可以通过设置scope=prototype来设置多实例
举例说明:
创建TestBean对象:
public class TestBean { }
配置xml文件, 不指定scope(或指定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="testBean" class="com.ryan.spring5.testScope.TestBean"></bean> </beans>
生成两个实例, 测试其地址相同:
按上例, 指定配置文件bean中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="testBean" class="com.ryan.spring5.testScope.TestBean" scope="prototype"></bean> </beans>
生成两个实例, 测试其地址不同: