7.Spring Bean的作用域

2018-03-15  本文已影响0人  Vincentl_Hui

Bean 的作用域

在Spring中定义一个Bean,Ioc容器可限制该bean作用于某个范围.

Bean的常用作用域

singleton的作用域 :
xml中的config
<?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="car" class="com.atguigu.spring.beans.Car"
    scope="singleton">
     <property name="brand" value="Audi"></property>
     <property name="price" value="30000"></property>
    </bean>

</beans>
Main.c
public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //1. 创建Spring 的IOC容器对象
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-scope.xml");
        
        //2.从IOC容器中获取bean 实例
        //利用id定位到IOC 容器中的Bean
        Car car = (Car) ctx.getBean("car");
        
        Car car2 = (Car) ctx.getBean("car");
        System.out.println(car == car2);
    }

}

运行结果:
信息: Loading XML bean definitions from class path resource [beans-scope.xml]
true
说明:

singleton属性限制了在IOC容器中,不再创建新的bean对象,唯独一个对象.

prototype的作用域
xml中的config
<?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="car" class="com.atguigu.spring.beans.Car"
    scope="prototype">
     <property name="brand" value="Audi"></property>
     <property name="price" value="30000"></property>
    </bean>

</beans>
Main.c
public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //1. 创建Spring 的IOC容器对象
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-scope.xml");
        
        //2.从IOC容器中获取bean 实例
        //利用id定位到IOC 容器中的Bean
        Car car = (Car) ctx.getBean("car");
        
        Car car2 = (Car) ctx.getBean("car");
        System.out.println(car == car2);
    }

}

运行结果:
信息: Loading XML bean definitions from class path resource [beans-scope.xml]
false
说明:

每次注入或请求要给bean的时候都创建一个新的bean

Bean的常用作用域总结
作用域 描述
singleton 整个应用中,只创建一个bean
prototype 每次注入或请求要给bean的时候都创建一个新的bean。
上一篇 下一篇

猜你喜欢

热点阅读