基于Xml方式的Bean的配置-Bean的作用范围scope配置

SpringBean的配置详解

  • Bean的配置范围

    • 默认情况下(基本的Spring环境),单纯Spring环境Bean的作用范围有两个:Singleton和prototype
    • singleton :单例,默认值,Spring容器创建的时候,就会进行Bean的实例化 ,并储存到Bean的内部的单例池中,每次getBean时都是从单例池中获取相同的Bean实例
    • prototype :原型,Spring容器初始化时不会创建Bena实例,当调用getBean时 才会实例化Bean,每次getBean都会创建一个新的Bean实例
  • 当scope=singleton时
    *

    XML 复制代码
        <bean id="userService" class="com.example.Service.Impl.UserServiceImpl" scope="singleton">
    java 复制代码
            ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
            Object userService1 = context.getBean("userService");
            Object userService2 = context.getBean("userService");
            Object userService3 = context.getBean("userService");
            System.out.println(userService1);
            System.out.println(userService2);
            System.out.println(userService3);
    • 运行结果如下:

  • 当scope=prototype时

    java 复制代码
        <bean id="userService" name="aaa,bbb" class="com.example.Service.Impl.UserServiceImpl" scope="prototype">
    java 复制代码
            ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
            Object userService1 = context.getBean("userService");
            Object userService2 = context.getBean("userService");
            Object userService3 = context.getBean("userService");
            System.out.println(userService1);
            System.out.println(userService2);
            System.out.println(userService3);
    • 运行结果

PS:如果添加了SpringWebMVC依赖,scope的值就有多个

XML 复制代码
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.7</version>
        </dependency>
相关推荐
untE EADO1 天前
Tomcat的server.xml配置详解
xml·java·tomcat
zuowei28891 天前
spring实例化对象的几种方式(使用XML配置文件)
xml·java·spring
weixin_520649871 天前
xml json ini 文件语法
xml·java·json
Full Stack Developme1 天前
Hutool XML 操作教程
xml·windows·python
阿亮爱学代码3 天前
初识Android界面布局
android·xml·view·viewgroup
eSsO KERF4 天前
使用 Logback 的最佳实践:`logback.xml` 与 `logback-spring.xml` 的区别与用法
xml·spring·logback
麻辣璐璐5 天前
EditText属性运用之适配RTL语言和LTR语言的输入习惯
android·xml·java·开发语言·安卓
awei09166 天前
MinIO配置自定义crossdomain.xml跨域策略(Nginx反向代理实现)
xml·java·nginx
那个失眠的夜8 天前
Spring 的纯注解配置
xml·java·数据库·后端·spring·junit