配置形式:基于 XML 文件的方式;基于注解的方式
在 xml 文件中通过 bean 节点来配置 bean:
<!-- 通过 bean 节点配置bean --> <bean id="helloWorld" class="com.atguigu.spring.helloworld.HelloWorld2"> <property name="name" value="ligang"></property> </bean>
id:Bean 的名称。 在 IOC 容器中必须是唯一的 若 id 没有指定,Spring 自动将权限定性类名作为 Bean 的名字 id 可以指定多个名字,名字之间可用逗号、分号、或空格分隔
Bean 的配置方式: 通过全类名(反射)、通过工厂方法(静态工厂方法 & 实例工厂方法)、FactoryBean
IOC 容器 BeanFactory & ApplicationContext 概述
在 Spring IOC 容器读取 Bean 配置创建 Bean 实例之前, 必须对它进行实例化. 只有在容器实例化后, 才可以从 IOC 容器里获取 Bean 实例并使用.
- BeanFactory: IOC 容器的基本实现.
- ApplicationContext: 提供了更多的高级特性. 是 BeanFactory 的子接口.
- BeanFactory 是 Spring 框架的基础设施,面向 Spring 本身;
- ApplicationContext 面向使用 Spring 框架的开发者,几乎所有的应用场合都直接使用 ApplicationContext 而非底层的 BeanFactory
- 无论使用何种方式, 配置文件时相同的.
ApplicationContext 的主要实现类:
- ClassPathXmlApplicationContext:从 类路径下加载配置文件
- FileSystemXmlApplicationContext: 从文件系统中加载配置文件s
- ConfigurableApplicationContext 扩展于 ApplicationContext,新增加两个主要方法:refresh() 和 close(), 让 ApplicationContext 具有启动、刷新和关闭上下文的能力
- ApplicationContext 在初始化上下文时就实例化所有单例的 Bean。
- WebApplicationContext 是专门为 WEB 应用而准备的,它允许从相对于 WEB 根目录的路径中完成初始化工作
从 IOC 容器中获取 Bean:
- 调用 ApplicationContext 的 getBean() 方法。
依赖注入的方式:
属性注入:
- 属性注入即通过 setter 方法注入Bean 的属性值或依赖的对象
- 属性注入使用 <property> 元素, 使用 name 属性指定 Bean 的属性名称,value 属性或 <value> 子节点指定属性值
- 属性注入是实际应用中最常用的注入方式
<!-- 属性注入配置bean --> <bean id="helloWorld" class="com.atguigu.spring.helloworld.HelloWorld2"> <property name="name" value="ligang"></property> </bean>
构造器注入:
- 通过构造方法注入Bean 的属性值或依赖的对象,它保证了 Bean 实例在实例化后就可以使用。
- 构造器注入在 <constructor-arg> 元素里声明属性, <constructor-arg> 中没有 name 属性
<!-- 若一个 bean 有多个构造器, 如何通过构造器来为 bean 的属性赋值 --> <!-- 可以根据 index 和 value 进行更加精确的定位. --> <bean id ="bus" class="com.atguigu.spring.helloworld.Bus" > <constructor-arg value="KUGA" index="1"></constructor-arg> <constructor-arg value="ChangAnFord" index="0"></constructor-arg> <constructor-arg value="250000" type="int"></constructor-arg> </bean>
public class Bus { private String name; private String brand; private double price; private int maxSpeed; public Bus(String name, String brand, int maxSpeed) { super(); this.name = name; this.brand = brand; this.maxSpeed = maxSpeed; } public Bus(String name, String brand, double price) { super(); this.name = name; this.brand = brand; this.price = price; } @Override public String toString() { return "myBus [name=" + name + ", brand=" + brand + ", price=" + price + ", maxSpeed=" + maxSpeed + "]"; } }
ClassPathXmlApplicationContext cpa = new ClassPathXmlApplicationContext("applicationContext.xml"); Bus bus = (Bus) cpa.getBean("bus"); System.out.println(bus.toString());
结果:
myBus [name=ChangAnFord, brand=KUGA, price=0.0, maxSpeed=250000]