Spring学习之从BeanFactory接口开始--Bean的作用域
先看一下BeanFactory接口的三个子接口:

还是很清楚的
- ListableBeanFactory:提供访问容器中bean基本信息的方法
- AutowireCapableBeanFactory:定义了将容器中的bean按某种方式进行自动装配的方法
- HierarchicalBeanFactory:提供了访问父容器的方法,这样就使得spring具有父子级联的IOC容器
看一下BeanFactory定义的方法

在BeanFactory中的方法,很普通,但是需要特别注意的是isPrototype,isSingleton这两个方法,因为这涉及到Bean的作用域的概念。
在isSingleton方法注释中是这样描述的
写道
Is this bean a shared singleton? That is, will getBean always return the same instance?
Note: This method returning false does not clearly indicate independent instances. It indicates non-singleton instances, which may correspond to a scoped bean as well. Use the isPrototype operation to explicitly check for independent instances.
既然Spring在如此核心的BeanFactory中已经涉及到singleton等概念了,那顺便复习一下。
singleton模式,是设计模式中的一种,中文名为单例模式,顾名思义,单例模式在实例化一次后每次只返回原有的那一份。这在数据库连接,一些共享,无状态的对象上非常有用,避免了每次实例化带来的开销。
核心提示点:Spring下默认的bean均为singleton,可以通过singleton=“true|false” 或者 scope=“?”来指定
关于singleton的概念,可以通过以下的代码来大致表现出来(代码为网上搜索得来^_^):
public class HelloBean {
private String helloWorld;
private int i = (int) (100 * Math.random());
public HelloBean(String helloWorld) {
this.helloWorld = helloWorld;
}
public void sayHello() {
System.out.println(helloWorld);
System.out.println("输出随机整数: " + i);
}
}
<beans>
<bean id="singletonBean" class="javamxj.spring.basic.singleton.HelloBean">
<constructor-arg>
<value>Hello! 这是singletonBean!value>
</constructor-arg>
</ bean>
<bean id="prototypeBean" class="javamxj.spring.basic.singleton.HelloBean"
singleton="false">
<constructor-arg>
<value>Hello! 这是prototypeBean! value>
</constructor-arg>
</bean>
</beans>
public class Main {
public static void main(String[] args) {
Resource res = new ClassPathResource("javamxj/spring/basic/singleton/bean.xml");
BeanFactory factory = new XmlBeanFactory(res);
HelloBean h1 = (HelloBean) factory.getBean("singletonBean");
h1.sayHello();
HelloBean h2 = (HelloBean) factory.getBean("singletonBean");
h2.sayHello();
System.out.println("h1==h2: " + (h1==h2));
System.out.println("");
HelloBean h3 = (HelloBean) factory.getBean("prototypeBean");
h3.sayHello();
HelloBean h4 = (HelloBean) factory.getBean("prototypeBean");
h4.sayHello();
System.out.println("h3==h4: " + (h3==h4));
}
}
运行结果为:
Hello! 这是singletonBean!
输出随机整数: 7
Hello! 这是singletonBean!
输出随机整数: 7
h1==h2: true
Hello! 这是prototypeBean!
输出随机整数: 95
Hello! 这是prototypeBean!
输出随机整数: 60
h3==h4: false
核心提示:Spring通过某些机制,保证了在其容器下的bean默认均为singleton,也就是说使用者无需自己维护一个singleton方法。
除了singleton作用域外,spring还有prototype,request,session,globalSession几个作用域,这些我在其他文章中再写!
总结一下:
- BeanFactory本质是一个工厂,创建Bean的工厂(涉及到工厂模式)
- 部分设计模式在Spring中有着非常重要的应用