- 作用域:
- singleton:单例模式,在整个Spring ioc容器中,singleton作用域的bean将只生成一个示例。
- prototype:每次通过容器的getBean()方法获取prototype作用域的bean时,都将产生一个新的bean实例。
- request:对于依次http请求,request作用域的bean都将只生成一个实例,在同一个http请求,程序每次请求该bean,得到的都是同一个实例。只有在web应用中使用spring时,该作用域才有效。
- session:对于一次http会话,session作用域的bean将只生成一个实例,程序每次请求该bean,得到的都是同一个实例。只有在web应用中使用spring时,该作用域才有效。
-global session:每个全局的http session对应一个bean实例。在典型情况下,仅在使用portlet context的时候有效。只有在web应用中使用spring时,该作用域才有效。
配置分别为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);
输出结果
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全部属性设置成功后执行特定行为
- 使用init-methd方法
- 实现InitializingBean接口,实现方法
void afterPropertiesSet() throws Exception;
注解使用@PostConstruct
2.2 Spring提供了两种方式在bean销毁之前的特定行为,
- 使用destroy-methd方法
- 实现DisposableBean接口,实现方法
void destroy() throws Exception;
注解使用@PreDestroy
网友评论