• Spring(七)—— bean的作用域


    一、bean的作用域

    类别

    说明

    singleton

    Spring IoC容器中仅存在一个Bean实例,Bean以单例方式存在,默认值

    prototype

    每次从容器中调用Bean时,都返回一个新的实例,即每次调用getBean()时 ,相当于执行new XxxBean()

    request

    每次HTTP请求都会创建一个新的Bean,该作用域仅适用于WebApplicationContext环境

    session

    同一个HTTP Session 共享一个Bean,不同Session使用不同Bean,仅适用于WebApplicationContext 环境

    globalSession

    一般用于Portlet应用环境,该作用域仅适用于WebApplicationContext 环境

     二、Singleton

    beans4.xml

    1 <!--bean的作用域:singleton单例,scope不写默认是单例-->
    2     <bean id="userService1" class="com.gyf.service.UserServiceImpl" scope="singleton"></bean>

    Lesson04.java

    package com.gyf.test;
    
    import com.gyf.service.IUserService;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Lesson04 {
        @Test
        public void test1(){
         //从容器中获取两个bean ApplicationContext context
    = new ClassPathXmlApplicationContext("beans4.xml"); IUserService userService1 = (IUserService) context.getBean("userService1"); IUserService userService2 = (IUserService) context.getBean("userService1"); System.out.println(userService1); System.out.println(userService2); System.out.println(userService1 == userService2);//比较内存地址,结果为true,相等 System.out.println(userService1.equals(userService2));//作用同上,比较内存地址,结果是true } }

    三、prototype

    beans.xml

    1 <!--bean的作用域:prototype多例-->
    2     <bean id="userService2" class="com.gyf.service.UserServiceImpl" scope="prototype"></bean>

    Lesson04.java

     1 package com.gyf.test;
     2 
     3 import com.gyf.service.IUserService;
     4 
     5 import org.junit.Test;
     6 import org.springframework.context.ApplicationContext;
     7 import org.springframework.context.support.ClassPathXmlApplicationContext;
     8 
     9 public class Lesson04 {
    10 
    11     @Test
    12     public void test2(){
          //从容器中获取两个bean
    13 ApplicationContext context = new ClassPathXmlApplicationContext("beans4.xml"); 14 IUserService userService1 = (IUserService) context.getBean("userService2"); 15 IUserService userService2 = (IUserService) context.getBean("userService2"); 16 System.out.println(userService1); 17 System.out.println(userService2); 18 System.out.println(userService1 == userService2);//false,内存地址不相等 19 System.out.println(userService1.equals(userService2)); 20 } 21 }
  • 相关阅读:
    聊一聊Flutter的setState()
    Flutter + Android 混合开发
    Flutter防止布局溢出
    Flutter获取远程数据 刷新UI界面
    Flutter日常笔记
    POJ 3299 Humidex
    POJ 1207 The 3n + 1 problem
    POJ 1005 I Think I Need a Houseboat
    POJ 1004 Financial Management
    POJ1012
  • 原文地址:https://www.cnblogs.com/upyang/p/13575150.html
Copyright © 2020-2023  润新知