零、作用域种类
spring 中有七种作用于:
一、简单讲解
Bean的作用于是通过 元素的 scope 属性来制定的,以singleton为例,示例代码如下:
<!--beans.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"> <!--使用singleton--> <bean id="scope" class="com.itheima.instance.scope.Scope" scope="singleton"/> </beans>
package com.itheima.instance.scope; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class ScopeTest { public static void main(String[] args) { String xmlPath = "com/itheima/instance/scope/beans4.xml"; ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath); //输出两次实例,在控制台可以看到两次的实例是一样的 System.out.println(applicationContext.getBean("scope")); System.out.println(applicationContext.getBean("scope")); } }