spring bean配置后再默认情况下是单例的,如果需要配置可以选择 prototype, request, session和global session
在配置spring mvc的action时,可以对action使用 prototype
1 <!-- singleton: 默认单例 prototype: 多例 request ,session和global session: 只适用于web程序 --> 2 <bean id="scope_prototype" class="com.lee.spring005.scope.Scope" 3 scope="prototype"></bean> 4 5 <!-- destroy-method 一般在数据源的时候用到,关闭容易后就销毁连接 --> 6 <bean id="initDestory" class="com.lee.spring006.init_destory.InitDestory" 7 init-method="init" destroy-method="destory"></bean>
bean的创建销毁过程:
1 package com.lee.spring006.init_destory; 2 3 public class InitDestory { 4 5 public InitDestory() { 6 System.out.println("InitDestory() "); 7 } 8 9 public void hello() { 10 System.out.println("Hello InitDestory!"); 11 } 12 13 public void init() { 14 System.out.println("init"); 15 } 16 17 public void destory() { 18 System.out.println("destory"); 19 } 20 }
测试:
1 @Test 2 public void testInitDestory() { 3 4 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 5 6 InitDestory initDestory = (InitDestory)context.getBean("initDestory"); 7 initDestory.hello(); 8 9 ClassPathXmlApplicationContext app = (ClassPathXmlApplicationContext)context; 10 app.close(); 11 }
github地址:https://github.com/leechenxiang/maven-spring001-helloworld