- 作用域:
- singleton:單例模式,在整個(gè)Spring ioc容器中,singleton作用域的bean將只生成一個(gè)示例。
- prototype:每次通過容器的getBean()方法獲取prototype作用域的bean時(shí),都將產(chǎn)生一個(gè)新的bean實(shí)例。
- request:對(duì)于依次http請(qǐng)求,request作用域的bean都將只生成一個(gè)實(shí)例,在同一個(gè)http請(qǐng)求,程序每次請(qǐng)求該bean,得到的都是同一個(gè)實(shí)例。只有在web應(yīng)用中使用spring時(shí),該作用域才有效。
- session:對(duì)于一次http會(huì)話,session作用域的bean將只生成一個(gè)實(shí)例,程序每次請(qǐng)求該bean,得到的都是同一個(gè)實(shí)例。只有在web應(yīng)用中使用spring時(shí),該作用域才有效。
-global session:每個(gè)全局的http session對(duì)應(yīng)一個(gè)bean實(shí)例。在典型情況下,僅在使用portlet context的時(shí)候有效。只有在web應(yīng)用中使用spring時(shí),該作用域才有效。
配置分別為sington和prototype
<bean name="user" class="com.lq.play.model.User" scope="singleton">
<property name="id" value="32324324"/>
<property name="username" value="singleton"/>
<property name="password" value="singleton"/>
<property name="salt" value="singleton"/>
</bean>
<bean name="user1" class="com.lq.play.model.User" scope="prototype">
<property name="id" value="23443235"/>
<property name="username" value="prototype"/>
<property name="password" value="prototype"/>
<property name="salt" value="prototype"/>
</bean>
測試代碼
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("config/spring/spring-servlet.xml");
User user0 = applicationContext.getBean("user", User.class);
System.out.println(user0);
User user = applicationContext.getBean("user", User.class);
System.out.println(user);
User user1 = applicationContext.getBean("user1", User.class);
System.out.println(user1);
User user2 = applicationContext.getBean("user1", User.class);
System.out.println(user2);
System.out.println(user0==user);
System.out.println(user1==user2);
輸出結(jié)果
User{id=32324324, username='singleton', password='singleton', salt='singleton', locked=false}
User{id=32324324, username='singleton', password='singleton', salt='singleton', locked=false}
User{id=23443235, username='prototype', password='prototype', salt='prototype', locked=false}
User{id=23443235, username='prototype', password='prototype', salt='prototype', locked=false}
true
false
- bean的生命周期
2.1 Spring提供了兩種方式在bean全部屬性設(shè)置成功后執(zhí)行特定行為
- 使用init-methd方法
- 實(shí)現(xiàn)InitializingBean接口,實(shí)現(xiàn)方法
void afterPropertiesSet() throws Exception;
注解使用@PostConstruct
2.2 Spring提供了兩種方式在bean銷毀之前的特定行為,
- 使用destroy-methd方法
- 實(shí)現(xiàn)DisposableBean接口,實(shí)現(xiàn)方法
void destroy() throws Exception;
注解使用@PreDestroy