在bean中配置作用域使用屬性scope來(lái)設(shè)置bean的作用域
-
scope="singleton" 也是bean配置中默認(rèn)的配置
bean配置文件代碼:
<bean id="school" class="com.example.demo.entity.School" scope="singleton"> <property name="schoolName" value="北京大學(xué)"></property> <property name="schoolAddress" value="北京市海淀區(qū)"></property> </bean>
java測(cè)試代碼:
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-scop.xml"); School school = (School) ctx.getBean("school"); School school1 = (School) ctx.getBean("school"); System.out.println(school); System.out.println(school1);
運(yùn)行結(jié)果:
School被創(chuàng)建 Disconnected from the target VM, address: '127.0.0.1:51820', transport: 'socket' com.example.demo.entity.School@4d5650ae com.example.demo.entity.School@4d5650ae Process finished with exit code 0
從上可以看出bean屬性scope為singleton時(shí)藏否,容器初始化時(shí)會(huì)創(chuàng)建實(shí)例,該容器中對(duì)象的實(shí)例有且只有一個(gè)
-
scope="prototype"
bean配置:
<bean id="school1" class="com.example.demo.entity.School" scope="prototype"> <property name="schoolName" value="清華大學(xué)"></property> <property name="schoolAddress" value="北京市海淀區(qū)"></property> </bean>
java測(cè)試代碼:
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-scop.xml"); School school = (School) ctx.getBean("school1"); School school1 = (School) ctx.getBean("school1"); System.out.println(school); System.out.println(school1);
運(yùn)行結(jié)果:
School被創(chuàng)建 School被創(chuàng)建 com.example.demo.entity.School@a38c7fe com.example.demo.entity.School@6fdbe764
從運(yùn)行結(jié)果可以看出bean屬性scope為prototype時(shí),容器初始化時(shí)不會(huì)創(chuàng)建bean的實(shí)例,只有在調(diào)用時(shí)才會(huì)創(chuàng)建bean的實(shí)例蜒蕾;
scope="request" 和 scope="session"
這兩個(gè)屬性都是涉及到與對(duì)象山林,一個(gè)是resquest域银受,兩一個(gè)是session域