Spring配置详解--Bean

Bean配置的解析

这里写图片描述

对象的三种创建方式

  • 空参构造方式
    这里写图片描述
  • 静态工厂(了解)
    这里写图片描述
  • 实例工厂
    这里写图片描述

Bean元素进阶—Scope属性

  • singleton(默认值):单例对象.被标识为单例的对象在spring容器中只会存在一个实例
  • prototype:多例原型.被标识为多例的对象,每次再获得才会创建.每次创建都是新的对象.
  • request(了解):web环境下.对象与request生命周期一致.
  • session(了解):web环境下,对象与session生命周期一致.
@Test
//scope:singleton 单例
//scope:prototype 多例
public void fun4(){
    //1 创建容器对象
    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    //2 向容器"要"user对象
    User u = (User) ac.getBean("user");
    User u2 = (User) ac.getBean("user");
    System.out.println(u==u2);//单例:true
                              //多例:false
    //3 打印user对象
    System.out.println(u);
}

对于scope的使用:一般情况下使用默认的singleton,只有在整合struts2时,ActionBean必须配置为多例的,因为struts2在设计上,每次请求都会创建一个新的action,所以必须是多例的,如果是单例的,同时有10个请求,spring给了10个请求同一个action,这样违背了struts2的架构

Bean元素进阶—生命周期(了解)
  • init-method
    配置一个方法作为生命周期初始化方法.spring会在对象创建之后立即调用.
  • destory-method
    配置一个方法作为生命周期的销毁方法.spring容器在关闭并销毁所有容器中的对象之前调用.
    这里写图片描述

Bean元素进—分模块配置

引入其他的配置文件
这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_42780864/article/details/81347984