详解Spring框架---IOC装配Bean

发布时间 - 2026-01-10 23:29:03    点击率:

IOC装配Bean

(1)Spring框架Bean实例化的方式提供了三种方式实例化Bean

  1. 构造方法实例化(默认无参数,用的最多)
  2. 静态工厂实例化
  3. 实例工厂实例化

下面先写这三种方法的applicationContext.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
  <!-- Bean的三种实例化方式=================== -->  
   <!-- 2.1 使用无参的构造器 -->
   <bean id="bean1" class="com.study.spring.b_instance.Bean1"></bean>
   <!-- 2.2使用静态工厂方法 factory-method 是工厂提供的静态方法 -->
   <bean id="bean2" class="com.study.spring.b_instance.Bean2" factory-method="createInstance"></bean>
   <!-- 2.3配置实例化工厂的方法 -->
   <bean id="bean3Factory" class="com.study.spring.b_instance.Bean3Factory"></bean>
   <bean id="bean3" factory-bean="bean3Factory" factory-method="getInstance"></bean>
  <!-- end.Bean的三种实例化方式==================== -->

Bean1类

public class Bean1 {
  
  //必须提供无参的构造函数 系统有默认无参的构造函数
}

Bean2类

public class Bean2 {
  private static Bean2 Bean2 = new Bean2();

  private Bean2() {
  }

  public static Bean2 createInstance() {
    return Bean2;
  }
}

Bean3类

public class Bean3 {

}

Bean3Factory类

public class Bean3Factory {
  
  private Bean3Factory(){
    
  }
   
  public Bean3 getInstance(){
    return new Bean3();
  }
}

测试类InstanceDemo

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class InstanceDemo {
  
  //实例化工厂方法
  @Test
  public void demo3(){
    //加载配置文件 创建工厂
    ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
    
    Bean3 bean3 =(Bean3) applicationContext.getBean("bean3");
    System.out.println(bean3);
    
  }
  
  //静态工厂方法
  @Test
  public void demo2(){
    //加载配置文件 创建工厂
    ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
    
    Bean2 bean2 =(Bean2) applicationContext.getBean("bean2");
    System.out.println(bean2);
    
  }
  //构造方法得到bean对象
  @Test
  public void demo1(){
    //加载配置文件 创建工厂
    ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
    
    Bean1 bean1 =(Bean1) applicationContext.getBean("bean1");
    System.out.println(bean1);
    
  }
}
/*
 * 这三个都得到类似于com.study.spring.b_instance.Bean1@7229c204 的内存地址
 */

 (2).Bean的其他配置:

一般情况下,装配一个Bean时,通过指定一个id属性作为Bean的名称

id 属性在IoC容器中必须是唯一的

id 的命名要满足XML对ID属性命名规范 必须以字母开始,可以使用字母、数字、连字符、下划线、句话、冒号

如果Bean的名称中含有特殊字符,就需要使用name属性 例如: <bean name="#person" class="cn.itcast.bean.Person"/>

因为name属性可以相同,所以后出现Bean会覆盖之前出现的同名的Bean

id和name的区别:

id遵守XML约束的id的约束.id约束保证这个属性的值是唯一的,而且必须以字母开始,可以使用字母、数字、连字符、下划线、句话、冒号

name没有这些要求

如果bean标签上没有配置id,那么name可以作为id.

Bean的scope属性

 <!-- 3.Bean的scope属性==================== -->  
   <bean id="product" class="com.study.spring.c_scope.Product" scope="singleton"></bean>
 <!-- end.Bean的scope属性=========== -->  

 * singleton :单例的.(默认的值.)

 * prototype :多例的.

* request :web开发中.创建了一个对象,将这个对象存入request范围,request.setAttribute();

* session :web开发中.创建了一个对象,将这个对象存入session范围,session.setAttribute();

* globalSession :一般用于Porlet应用环境.指的是分布式开发.不是porlet环境,globalSession等同于session;

3.Bean属性的依赖注入

前面已经知道如何获得对象,那我们接下来要知道如果给对象对象的属性赋值。

 

下面通过举例说明: 

Car 类

public class Car {

  private String name;

  private double price;

  public Car(String name, double price) {
    super();
    this.name = name;
    this.price = price;
  }

  @Override
  public String toString() {
    return "Car [name=" + name + ", price=" + price + "]";
  }
}

Car2类

public class Car2 {
  private String name;

  private double price;

  public void setName(String name) {
    this.name = name;
  }

  public void setPrice(double price) {
    this.price = price;
  }

  @Override
  public String toString() {
    return "Car2 [name=" + name + ", price=" + price + "]";
  }

}

CarInfo类

public class CarInfo {
  
  public String getName(){
    return "哈弗H6";
  }
  
  public double caculatePrice(){
    return 110000;
  }
}

CollectionBean类

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class CollectionBean {
  private String name;

  private Integer age;

  private List<String> hobbies;

  private Set<Integer> numbers;

  private Map<String, String> map;

  private Properties properties;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Integer getAge() {
    return age;
  }

  public void setAge(Integer age) {
    this.age = age;
  }

  public List<String> getHobbies() {
    return hobbies;
  }

  public void setHobbies(List<String> hobbies) {
    this.hobbies = hobbies;
  }

  public Set<Integer> getNumbers() {
    return numbers;
  }

  public void setNumbers(Set<Integer> numbers) {
    this.numbers = numbers;
  }

  public Map<String, String> getMap() {
    return map;
  }

  public void setMap(Map<String, String> map) {
    this.map = map;
  }

  public Properties getProperties() {
    return properties;
  }

  public void setProperties(Properties properties) {
    this.properties = properties;
  }

  @Override
  public String toString() {
    return "CollectionBean [name=" + name + ", age=" + age + ", hobbies=" + hobbies + ", numbers=" + numbers
        + ", map=" + map + ", properties=" + properties + "]";
  }
  
}

Employee类

public class Employee {

  private String name;

  private Car2 car2;

  public void setName(String name) {
    this.name = name;
  }

  public void setCar2(Car2 car2) {
    this.car2 = car2;
  }

  @Override
  public String toString() {
    return "Employee [name=" + name + ", car2=" + car2 + "]";
  }

}

TestDi测试类

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDi {
  
  @Test
  public void demo6() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

    CollectionBean collectionBean = (CollectionBean) applicationContext.getBean("collectionBean");

    System.out.println(collectionBean);
  }
  
  
  @Test
  public void demo5() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

    Car2 car2 = (Car2) applicationContext.getBean("car2_2");

    System.out.println(car2);
  }
  
  
  @Test
  public void demo4() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

    Employee e = (Employee) applicationContext.getBean("employee2");

    System.out.println(e);
  }
  
  @Test
  public void demo3() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

    Employee e = (Employee) applicationContext.getBean("employee");

    System.out.println(e);
  }

  @Test
  public void demo2() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

    Car2 car2 = (Car2) applicationContext.getBean("car2");

    System.out.println(car2);
  }

  @Test
  public void demo1() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

    Car car = (Car) applicationContext.getBean("car");

    System.out.println(car);
  }
}

上面这几个类都不是最主要的,我们主要是来看配置文件怎么写,这才是最关键的:

applicationContext.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  
  
  <!-- Bean的依赖注入=========== -->  
   <!-- 4.1构造器注入 -->
    <bean id="car" class="com.study.spring.e_di.Car">
      <!-- 方式一.根据索引的位置 -->
      <!-- <constructor-arg index="0" value="保时捷"></constructor-arg>
       <constructor-arg index="1" value="1500000"></constructor-arg> -->
       <!-- 方式二.根据名字配置 -->
       <!-- <constructor-arg name="name" value="宝马"></constructor-arg>
       <constructor-arg name="price" value="500000"></constructor-arg> -->
       <!-- 方式三.根据类型配置 -->
       <constructor-arg type="java.lang.String" value="奔驰"></constructor-arg>
       <constructor-arg type="double" value="600000"></constructor-arg>
    </bean>
    
   <!-- 4.2setter方法中注入 --> 
   <bean id="car2" class="com.study.spring.e_di.Car2">
     <property name="name" value="雪佛兰"></property>
     <property name="price" value="100000"></property>
   </bean>
   
   <bean id="employee" class="com.study.spring.e_di.Employee">
     <property name="name" value="张三"></property>
     <property name="car2" ref="car2"></property>
   </bean>
   
   <!-- 引用p命名空间 --><!-- 如果要引用p命名,那在最上面sxd中就要配置 xmlns:p="http://www.springframework.org/schema/p"-->
    <bean id="car22" class="com.study.spring.e_di.Car2" p:name="宝马" p:price="500000">
   </bean>
   <bean id="employee2" class="com.study.spring.e_di.Employee" p:name="李四" p:car2-ref="car22"></bean>
   
    <!-- 引入spEL表达式 -->
   <bean id="carInfo" class="com.study.spring.e_di.CarInfo"></bean>
    <bean id="car2_2" class="com.study.spring.e_di.Car2">
      <property name="name" value="#{carInfo.name}"></property>
      <property name="price" value="#{carInfo.caculatePrice()}"></property>
    </bean>
    
   <!-- 复杂属性的依赖注入 -->  
    <bean id="collectionBean" class="com.study.spring.e_di.CollectionBean">
      <!-- 简单属性的注入 -->
      <property name="name" value="归谷"></property>
      <property name="age" value="12"></property>
      <!-- 注入list集合 -->
       <property name="hobbies">
         <list>
           <value>吃饭</value>
           <value>睡觉</value>
           <value>敲代码</value>
         </list>
       </property>
       
       <!-- 注入set集合 -->
       <property name="numbers">
         <set>
           <value>10</value>
           <value>20</value>
           <value>30</value>
           <value>40</value>
           <value>50</value>
         </set>
       </property>
       <!-- 注入map集合 -->
       <property name="map">
         <map>
           <entry key="birthday" value="2017-1-1"></entry>
           <entry key="address" value="杭州西湖"></entry>
           <entry key="sex" value="female"></entry>
         </map>
       </property>
       
       <!-- 注入Properties -->
       <property name="properties">
         <props>
           <prop key="compamy">杭州归谷</prop>
           <prop key="pnum">200</prop>
         </props>
       </property>
    </bean>
    
  <!-- end Bean的依赖注入============ -->  
  <import resource="classpath:bean1.xml"/>    
  <import resource="classpath:bean2.xml"/>    
  <!-- 这里导入是指如果在src下还有其它的beans.xml我们可以这样去调用 -->  
    
</beans>

有关applicationContext.xml这个配置文件里的内容一定要看懂,我写的还是比较基础和全面的。

有关命名空间p的使用我这里在解释下:   

p:<属性名>="xxx" 引入常量值

p:<属性名>-ref="xxx" 引用其它Bean对象

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


# spring  # ioc  # bean  # 实例化bean  # spring装配bean  # 基于SpringIOC创建对象的四种方式总结  # SpringIOC框架的简单实现步骤  # Spring之IOC详解  # Spring(二):Spring通过IOC来创建对象  # Spring框架开发IOC两种创建工厂方法详解  # 配置文件  # 三种  # 下划线  # 加载  # 可以使用  # 句话  # 雪佛兰  # 保时捷  # 最多  # 是指  # 是唯一  # 我们可以  # 要知道  # 杭州  # 种方法  # 最主要  # 这几个  # 指的是  # 类似于  # 这三个 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: 如何快速选择适合个人网站的云服务器配置?  如何快速搭建高效香港服务器网站?  Angular 表单中正确绑定输入值以确保提交与验证正常工作  浅谈javascript alert和confirm的美化  如何快速辨别茅台真假?关键步骤解析  Laravel Artisan命令怎么自定义_创建自己的Laravel命令行工具完全指南  手机软键盘弹出时影响布局的解决方法  网站建设保证美观性,需要考虑的几点问题!  济南网站建设制作公司,室内设计网站一般都有哪些功能?  Laravel用户认证怎么做_Laravel Breeze脚手架快速实现登录注册功能  历史网站制作软件,华为如何找回被删除的网站?  Mybatis 中的insertOrUpdate操作  个人摄影网站制作流程,摄影爱好者都去什么网站?  Laravel怎么导出Excel文件_Laravel Excel插件使用教程  Python结构化数据采集_字段抽取解析【教程】  Laravel如何自定义错误页面(404, 500)?(代码示例)  Laravel怎么实现前端Toast弹窗提示_Laravel Session闪存数据Flash传递给前端【方法】  laravel怎么使用数据库工厂(Factory)生成带有关联模型的数据_laravel Factory生成关联数据方法  原生JS获取元素集合的子元素宽度实例  Windows10电脑怎么查看硬盘通电时间_Win10使用工具检测磁盘健康  Laravel怎么实现验证码功能_Laravel集成验证码库防止机器人注册  如何快速搭建高效WAP手机网站?  专业型网站制作公司有哪些,我设计专业的,谁给推荐几个设计师兼职类的网站?  laravel怎么为API路由添加签名中间件保护_laravel API路由签名中间件保护方法  Laravel怎么使用Blade模板引擎_Laravel模板继承与Component组件复用【手册】  Laravel数据库迁移怎么用_Laravel Migration管理数据库结构的正确姿势  Laravel的契約(Contracts)是什么_深入理解Laravel Contracts与依赖倒置  Laravel全局作用域是什么_Laravel Eloquent Global Scopes应用指南  宙斯浏览器怎么屏蔽图片浏览 节省手机流量使用设置方法  Laravel如何使用.env文件管理环境变量?(最佳实践)  消息称 OpenAI 正研发的神秘硬件设备或为智能笔,富士康代工  python中快速进行多个字符替换的方法小结  Laravel怎么写单元测试_PHPUnit在Laravel项目中的基础测试入门  php后缀怎么变mp4格式错误_修改扩展名提示格式不对怎么办【技巧】  Laravel如何与Docker(Sail)协同开发?(环境搭建教程)  Laravel怎么判断请求类型_Laravel Request isMethod用法  谷歌浏览器如何更改浏览器主题 Google Chrome主题设置教程  如何用VPS主机快速搭建个人网站?  Laravel如何处理CORS跨域问题_Laravel项目CORS配置与解决方案  如何注册花生壳免费域名并搭建个人网站?  制作旅游网站html,怎样注册旅游网站?  html5如何实现懒加载图片_ intersectionobserver api用法【教程】  如何在万网自助建站平台快速创建网站?  Windows10怎样连接蓝牙设备_Windows10蓝牙连接步骤【教程】  Laravel如何发送邮件_Laravel Mailables构建与发送邮件的简明教程  javascript读取文本节点方法小结  极客网站有哪些,DoNews、36氪、爱范儿、虎嗅、雷锋网、极客公园这些互联网媒体网站有什么差异?  EditPlus 正则表达式 实战(3)  如何在阿里云完成域名注册与建站?  Google浏览器为什么这么卡 Google浏览器提速优化设置步骤【方法】