Bean作用域和生命周期(三)

ScopeDescription
singletonThis scopes the bean definition to a single instance per Spring IoC container (default).
prototypeThis scopes a single bean definition to have any number of object instances.
requestThis scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
sessionThis scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
global-sessionThis scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

BeanScope.java

public class BeanScope{
  public void say(){
    System.out.pringln("BeanScope say"+this.hashCode());

}

}
spring-beanscope.xml

<?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="beanScope" class="com.imooc.bean.BeanScope" scope="singleton"></bean>
</beans>

  

TestBeanScope.java
import org.junit.Test;
import org.junit.Runwith;
import org.junit.runners.BlockJUnit4ClassRunner;
import com.imooc.test.base.UnitTestBase

@RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanScope extends UnitsTestBase{
   public TestBeanScope(){
     super("classpath*:spring-beanscope.xml"); //传入配置文件来启动ioc容器
}
@Test
public void testSay(){
  BeanScope beanScope=super.getBean("beanScope");
  beanScope.say();

 BeanScope beanScope2=super.getBean("beanScope");
  beanScope2.say();
}
}



如果
public void testSay(){
  BeanScope beanScope=super.getBean("beanScope");
  beanScope.say();
}

public void testSay2(){
  BeanScope beanScope=super.getBean("beanScope");
  beanScope.say();
}
hashcode是不一样的因为 执行testSay()有before和after, 是从两个bean的ioc容器里产生的。


生命周期
定义
初始化
使用
销毁


初始化
 实现org.springframework.beans.factory.InitializingBean接口,覆盖afterPropertiesSet方法


 配置init-method










销毁
 实现org.springframework.beans.factory.DisposableBean接口,覆盖destroy方法


 配置destroy-method









配置全局默认初始化销毁方法




BeanLifeCycle.java







评论

此博客中的热门博文

openflow switch(I)

YANG Tools:YANG to Java Mapping

OpenDaylight架构简介