IOC & DI 概述
配置 bean
配置形式:基于 XML 文件的方式;基于注解的方式
Bean 的配置方式:通过全类名(反射)、通过工厂方法(静态工厂方法 & 实例工厂方法)、FactoryBean
IOC 容器 BeanFactory & ApplicationContext 概述
依赖注入的方式:属性注入;构造器注入
注入属性值细节
自动装配
bean 之间的关系:继承;依赖
bean 的作用域:singleton;prototype;WEB 环境作用域
使用外部属性文件
IOC 容器中 Bean 的生命周期
在 Spring 的 IOC 容器里配置 Bean
在 xml 文件中通过 bean 节点来配置 bean
id:Bean 的名称。
在 IOC 容器中必须是唯一的
若 id 没有指定,Spring 自动将权限定性类名作为 Bean 的名字
id 可以指定多个名字,名字之间可用逗号、分号、或空格分隔
Spring 容器
在 Spring IOC 容器读取 Bean 配置创建 Bean 实例之前, 必须对它进行实例化. 只有在容器实例化后, 才可以从 IOC 容器里获取 Bean 实例并使用.
Spring 提供了两种类型的 IOC 容器实现.
BeanFactory: IOC 容器的基本实现.
ApplicationContext: 提供了更多的高级特性. 是 BeanFactory 的子接口.
BeanFactory 是 Spring 框架的基础设施,面向 Spring 框架本身;ApplicationContext 面向使用 Spring 框架的开发者,几乎所有的应用场合都直接使用 ApplicationContext 而非底层的 BeanFactory
无论使用何种方式, 配置文件是相同的.
ApplicationContext
ApplicationContext 的主要实现类:
ClassPathXmlApplicationContext:从 类路径下加载配置文件
FileSystemXmlApplicationContext: 从文件系统中加载配置文件
ConfigurableApplicationContext 扩展于 ApplicationContext,新增加两个主要方法:refresh() 和 close(), 让 ApplicationContext 具有启动、刷新和关闭上下文的能力
ApplicationContext 在所有单例的 Bean。初始化上下文时就实例化
WebApplicationContext 是专门为 WEB 应用而准备的,它允许从相对于 WEB 根目录的路径中完成初始化工作
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
id:bean的唯一标识
class:指定全类名 反射的方式创建对象:
Class cls = Class.forName("com.learn.spring.beans.HelloWorld")
Object obj = cls.newInstance(); // 需要提供默认的构造器.
property: 通过set方法给指定的属性赋值
-->
<bean id="helloWorld" class="com.learn.spring.beans.HelloWorld">
<property name="name1" value="Jerry"></property>
</bean>
<!-- 目前的配置,SpringIOC容器在实例化的时候都会创建bean对象. scope="singleton"-->
<bean id="helloWorld1" class="com.learn.spring.beans.HelloWorld" scope="singleton">
<property name="name1" value="Jerry"></property>
</bean>
</beans>
package com.learn.spring.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.learn.spring.beans.Book;
import com.learn.spring.beans.Car;
import com.learn.spring.beans.HelloWorld;
import com.learn.spring.beans.Person;
import com.learn.spring.beans.PersonList;
import com.learn.spring.beans.PersonMap;
public class Main {
public static void main(String[] args) {
/*//1.new 对象
HelloWorld helloWorld = new HelloWorld();
//2.给name属性赋值
helloWorld.setName("Tom");
*/
//1.获取IOC容器
ApplicationContext ctx =
new ClassPathXmlApplicationContext("applicationContext.xml");
//2.从IOC容器中获取对象.
//HelloWorld helloWorld = (HelloWorld)ctx.getBean("helloWorld");
//通过class去匹配bean,注意:如果有多个类型兼容的bean,会有问题.
//HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
HelloWorld helloWorld = ctx.getBean("helloWorld",HelloWorld.class);
//3.调用方法
helloWorld.sayHello();
}
}