Spring控制反转容器的使用

主要介绍Spring如何管理bean和依赖关系。

通过构造器创建一个bean的实例

之前的方法中,可以通过调用ApolicationContext的getBean方法可以获取到一个bean的实例。下面的配置文件中定义了一个名为product的bean。

[html] view plain copy print?
<span style="font-size:14px;"><?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:tx="http://www.springframework.org/schema/tx"  xmlns:context="http://www.springframework.org/schema/context"  xmlns:mvc="http://www.springframework.org/schema/mvc"  xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">  <!-- demo2 -->  <bean name="product" class="cn.redis.model.Product"></bean>  </beans></span>  

该bean的定义告诉Spring通过无参的构造来初始化product类。如果不存在该构造器(如果类作者重载了构造器,且没有显示声明默认构造器),则Spring将抛出一个异常。

ps:

应采用id或者name属性表示一个bean。为了让Spring创建一个Product实例,应将Bean定义的name值“product”(具体实践也可以是id值)和Product类型作为参数传递给ApplicationContext的getBean方法。

  1. [java] view plain copy print?
    public void test1(){  ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"config1.xml"});  Product product = context.getBean("Product",Product.class);  product.setName("www");  System.out.println("product:"+product.getName());  }  

     通过工厂方法创建一个bean实例

    除了通过类的构造器方法Spring还同样支持通过调用一个工厂的方法来初始化类。下面的bean定义展示了通过工厂方法来实例化java.uti.Calendar

  2. [html] view plain copy print?
    <bean name = "calendar" class="java.util.Calendar"  factory-method="getInstance"/>  

    DestroyMethod的使用

    有时,我们希望在一些类被销毁前能执行一些方法,Spring考虑到了这样的需求,可以在bean定义中配置destroy-method属性,来指定在销毁前要执行的方法。

    下面的例子中,配置Spring通过java.util.concurrent.Executors的静态方法newCachedThreadPool来创建一个java.util.concurrent.ExecutorService实例,并指定了destroy-method属性为shutdown方法。这样,Spring会在销毁ExecutorService实例前调用shutdown方法。

  3. [html] view plain copy print?
    <bean id="executors" class="java.util.concurrent.Executors"  factory-method="newCachedThreadPool"  destroy-method="newCachedThreadPool"/>  

    向构造器传递参数

    spring 支持通过带参数的构造器来初始化类

    proudct类

  4. [java] view plain copy print?
    public class Product implements Serializable {  private static final long serialVersionUID = 1L;  private String name;  private String description;  private float price;  public Product() {  }  public Product(String name,String description,float price) {
    <span style="white-space:pre">        </span>this.name=name;
    <span style="white-space:pre">        </span>this.description = description;
    <span style="white-space:pre">        </span>this.price=price;
    <span style="white-space:pre">    </span>}  public String getName() {  return name;  }  public void setName(String name) {  this.name = name;  }  public String getDescription() {  return description;  }  public void setDescription(String description) {  this.description = description;  }  public float getPrice() {  return price;  }  public void setPrice(float price) {  this.price = price;  }  }  如下定义展示了如何通过参数名传递参数
    [html] view plain copy print?
    <bean name="featuredProduct" class="cn.redis.model.Product">  <constructor-arg name="name" value="Ultimate Olive Oil" />  <constructor-arg name="description" value="The purest olive oil on the market" />  <constructor-arg name="price" value="9.95" />  </bean>
    这样在创建product实例时,Spring会调用如下构造器。
    [java] view plain copy print?
    public Product(String name,String description,float price) {  this.name=name;  this.description = description;  this.price=price;  }  

    除了通过名称传递参数外,Spring还支持通过指数方式传递参数,具体如下:

    [html] view plain copy print?
    <bean name="featuredProduct2" class="cn.redis.model.Product">  <constructor-arg index="0" value="Ultimate Olive Oil" />  <constructor-arg index="1"  value="The purest olive oil on the market" />  <constructor-arg index="2" value="9.95" />  </bean>  

    Setter 方式依赖注入

    下面以employee类和address类为例,说明setter方式依赖注入。

  5. [java] view plain copy print?
    package cn.redis.model;  public class Employee {  private String firstName;  private String lastName;  private Address homeAddress;  public Employee() {  }  public Employee(String firstName, String lastName, Address homeAddress) {  super();  this.firstName = firstName;  this.lastName = lastName;  this.homeAddress = homeAddress;  }  public String getFirstName() {  return firstName;  }  public void setFirstName(String firstName) {  this.firstName = firstName;  }  public String getLastName() {  return lastName;  }  public void setLastName(String lastName) {  this.lastName = lastName;  }  public Address getHomeAddress() {  return homeAddress;  }  public void setHomeAddress(Address homeAddress) {  this.homeAddress = homeAddress;  }  @Override  public String toString() {  return "Employee [firstName=" + firstName + ", lastName=" + lastName  + ", homeAddress=" + homeAddress + "]";  }  }  

    [java] view plain copy print?
    package cn.redis.model;  public class Address {  private String line1;  private String city;  private String state;  private String zipCode;  private String country;  public Address(String line1, String city, String state, String zipCode,  String country) {  super();  this.line1 = line1;  this.city = city;  this.state = state;  this.zipCode = zipCode;  this.country = country;  }  // getters and setters onitted  @Override  public String toString() {  return "Address [line1=" + line1 + ", city=" + city + ", state="  + state + ", zipCode=" + zipCode + ", country=" + country + "]";  }  }  

    Employee 依赖于Address类,可以通过如下配置来保证每一个Employee实例都能包含Address类

    [html] view plain copy print?
    <bean name="simpleAddress" class="cn.redis.model.Address">  <constructor-arg name="line1" value="151 corner" />  <constructor-arg name="city" value="Albany" />  <constructor-arg name="state" value="NY" />  <constructor-arg name="zipCode" value="99999" />  <constructor-arg name="country" value="US" />  </bean>  <bean name="employee" class="cn.redis.model.Employee">  <constructor-arg name="firstName" ref="simpleAddress" />  <constructor-arg name="lastName" value="Junio" />  <constructor-arg name=" homeAddress " value="Moore" />  </bean>  

    simpleAddress 对象是Address类的一个实例,其通过构造器方式实例化。employee对象则通过配置property元素来调用setter方法设置值,需要注意的是,homeAddress属性配置是simpleAddress对象的引用。被引用对象的配置定义无须早于引用其对象的定义。本例中,employee1对象可以出现在simpleAdress 对象定义之前。

    构造器方式的依赖注入

    我们还可以将Address对象通过构造器注入,如下所示

    [html] view plain copy print?
    <bean name="employee2" class="cn.redis.model.Employee">  <constructor-arg name="homeAddress"  ref="simpleAddress"/>  <constructor-arg name="firstName"  value="w"/>  <constructor-arg name="lastName"  value="qq"/>  </bean>  

    [html] view plain copy print?
    <bean name="simpleAddress" class="cn.redis.model.Address">  <constructor-arg name="line1" value="151 corner" />  <constructor-arg name="city" value="Albany" />  <constructor-arg name="state" value="NY" />  <constructor-arg name="zipCode" value="99999" />  <constructor-arg name="country" value="US" />  </bean>  

转载于:https://www.cnblogs.com/Angella/p/6502869.html

spring mvc 学习指南二相关推荐

  1. Spring MVC学习指南(11-12章总结)

    11:上传文件 将介绍如何在SpringMVC中使用Commons FileUpload和Servlet 3上传文件. 在填写表单的html中,必须将html的enctype属性值设置为multipa ...

  2. Spring MVC学习指南(1-4章总结)

    Spring 框架 1.0 前言 依赖注入: 构造器(构造注入) set方法(设值注入) filed方式 (必须引入org......anntation.Autowired) 如何配置依赖注入: XM ...

  3. spring mvc 学习指南一

    Spring框架 依赖注入技术,作为代码可测试性的一个解决方案已经被广泛应用,很多人在使用中并不区分依赖注入和控制反转(IOC) 简单来说,依赖注入的情况如下,有两个组件A和B,A依赖与B.假定A是一 ...

  4. Spring MVC学习指南(5-7章总结)

    列表内容 5:数据绑定和表单标签 数据绑定是指将用户输入绑定到领域模型(domain). 表单标签库包含了 可以在JSP页面中渲染HTML元素的标签. 典型的有form.input.options等. ...

  5. Spring MVC 学习总结(二)——控制器定义与@RequestMapping详解

    Spring MVC 学习总结(二)--控制器定义与@RequestMapping详解 目录 一.控制器定义 1.1.实现接口Controller定义控制器 1.2.使用注解@Controller定义 ...

  6. Spring MVC 入门指南(二):@RequestMapping用法详解

    为什么80%的码农都做不了架构师?>>>    一.@RequestMapping 简介 在Spring MVC 中使用 @RequestMapping 来映射请求,也就是通过它来指 ...

  7. Spring MVC 学习总结(九)——Spring MVC实现RESTful与JSON(Spring MVC为前端提供服务)...

    Spring MVC 学习总结(九)--Spring MVC实现RESTful与JSON(Spring MVC为前端提供服务) 目录 一.JSON 1.1.概要 1.2.使用ModelAndView ...

  8. Spring MVC 学习总结(一)——MVC概要与环境配置 转载自【张果】博客

    Spring MVC 学习总结(一)--MVC概要与环境配置 目录 一.MVC概要 二.Spring MVC介绍 三.第一个Spring MVC 项目:Hello World 3.1.通过Maven新 ...

  9. Spring MVC 学习总结(五)——校验与文件上传 转自 张果 博客;已经编程校验;正确无误;...

    Spring MVC 学习总结(五)--校验与文件上传 目录 一.Spring MVC验证器Validator 1.1.定义验证器 1.2.执行校验 1.3.在UI中添加错误标签 1.4.测试运行 二 ...

最新文章

  1. 在MATPLOTLIB中加入汉字显示
  2. 谷歌旗下Waymo开启数据集虚拟挑战赛
  3. Ubuntu 安装配置Git过程记录
  4. Android中的音乐播放
  5. 技术解析:如何用pyecharts绘制时间轮播图
  6. 我的工作日报 - 2020-9-11 星期五
  7. lstrip在python中是什么意思_什么是一目均衡图?如何利用一目均衡图来做交易?...
  8. 马斯克再带货狗狗币:超7成网友票选狗狗币为未来货币
  9. 死链提交为什么不能提交 html文件,百度提交网站后死链一直未处理掉的原因有哪些?...
  10. 浅谈函数的重入与不可重入
  11. 为什么字节跳动、腾讯、阿里都在用 Python??
  12. 车位编号lisp_CAD自动编号操作
  13. spring mvc 从Controller向页面传数据
  14. 批量复制文件夹的批处理.bat命令
  15. 单应性变换 Homography Estimation
  16. Ceres Solver介绍
  17. cad2010背景怎么调成黑色_iOS14桌面怎么布局好看-热点资讯-
  18. 下载mysql源码包
  19. Paddle-Lite - 华为 NPU - softmax
  20. PythonQt——yolov5手势识别隔空操纵车载音乐播放器

热门文章

  1. Python实现一个键盘记录器功能
  2. python无法初始化设备_无法初始化图形设备什么意思
  3. 一篇评价牛顿的搞笑文章,作者老罗,但很有才
  4. python3入门指南_Python 3.4入门指南
  5. ReactiveUI 入门
  6. 证明ker f是H中的闭线性子空间(f是连续有界线性泛函)
  7. HOJ 2550 百步穿杨
  8. 工业生产中的“主动刹车”,是怎么实现的?
  9. sdoi2009 [动态规划 状态压缩DP] 学校食堂
  10. unity碰撞检测函数,碰撞信息获取,触发检测,使用粒子系统创建火焰,创建动画(火光闪烁),导航系统,通过导航系统控制人物移动,控制摄像机的跟随,控制角色动画播放