spring学习09:Bean的作用域

spring学习09:Bean的作用域

  • Bean的作用域:

    Scope作用域描述
    singleton:单例 (默认)全局共享一个;对象只会创建一次;
    protoType:原型 每个 bean 调用的时候,都会单独创建对象。

     

  • 单例模式:

    • 显式设置为单例模式:scope="singleton"

      <bean id="address" class="com.ljxdemo.pojo.Address" scope="singleton">
         <property name="address" value="海南省xxxx号"/>
      </bean>

 

  • 原型模式:

    • bean设置为原型模式:scope="prototype";

    • 每次从容器中get的时候,都会产生一个新对象;

      <bean id="address" class="com.ljxdemo.pojo.Address" scope="prototype">
         <property name="address" value="海南省xxxx号"/>
      </bean>

       

 

  • 其他:这些只能在web开发中使用

    • request

    • session

    • application

 

 

  • 代码案例: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"
          xmlns:p="http://www.springframework.org/schema/p"
          xmlns:c="http://www.springframework.org/schema/c"
          xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">

       <!-- p命名空间注入,可以直接注入属性的值: -->
       <bean id="user" class="com.ljxdemo.pojo.User" scope="singleton" p:age="11" p:name="demo"/>

       <!-- c命名空间注入,通过构造器注入:constructor-arg -->
       <bean id="user2" class="com.ljxdemo.pojo.User" scope="prototype" c:age="11" c:name="张三" />

    </beans>
  • 代码案例:测试类

    public class MyTest2 {

       @Test
       public void test(){
           ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
           User user = (User) context.getBean("user2");
           User user2 = (User) context.getBean("user2");
           System.out.println(user==user2);
      }
    }

      

 

posted @   gzs1024  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示