spring 管理的 bean 是根据 scope 来生成的,表示 bean 的作用域,共四种。
-
singleton:单例,表示通过 IoC 容器获取的 bean 是唯一的。
- scope 默认为 singleton
ApplicationContext ctx=new ClassPathXmlApplicationContext("Spring.xml"); Student student=(Student)(ctx.getBean("student1")); Student student2=(Student)(ctx.getBean("student1")); System.out.println(student==student2); //Ture -
prototype:原型,表示通过 IoC 容器获取的 bean 是不同的。
-
request: 请求,表示再一次 HTTP 请求内有效。
-
session:会话,表示在一个用户会话内有效。
request 和 session 只适用于 Web 项目,大多数情况下,使用单例(singleton)和模型(prototype)。
singleton 模式无论业务代码是否获取 IoC 容器中的 bean,Spring 在加载 spring.xml 时就会创建 bean 。
prototype 模式当业务代码获取 IoC 容器中的 bean 时,Spring 才回去调用午餐构造创建对应的 bean。
Spring 的继承与 java 的继承不同,java 是类层面的继承, 子类可以继承父类的内部结构信息;Spring 是对象层面的继承,子对象可以继承父对象的属性值。
继承的同时还可以覆盖。
Spring 的继承的关注点在于具体的对象,而不在于类,即不同的两个类的实例化对象可以完成继承,前提是子对象必须包含父对象所有属性,同时可以在此基础上添加其他属性。



