一、 IOC前生:分离接口和实现
二、IOC&DI采用工厂设计模式
ReportService知道接口类型并且指向工厂,工厂来生成接口实现类
三、IOC-采用反转控制
容器把servlet实现类注入给ReportService
配置bean
-配置形式:
1.基于XML
<bean id = "helloWord" class="com.spring.beans.HelloWorld">
</bean>
2.基于注解
-Bean 的配置方式:通过全类名(反射)
-IOC 容器 BeanFactory & ApplicationContext 概述
1.BeanFactory IOC基本实现;底层,面向Spring本身
2.ApplicationContext 提供更多高级特性,前者子接口,面向Spring框架开发者
-依赖注入的方式:属性注入;构造器注入
属性注入: setter方法属性注入
使用 元素, 使用 name 属性指定 Bean 的属性名称,value 属性或 子节点指定属性值
构造器注入:通过构造器注入属性值可以指定参数位置和类型区分重载
<bean id="**" class="com.spring.beans.**">
<constructor-arg value = "**" index ="0"></constructor-arg>
<constructor-arg value = "**" index = "1"></constructor-arg>
<!--
<constructor-arg value = "***" type="java.lang.String"></constructor-arg>
-->
</bean>
HELLOWorld项目
1.新建HelloWorld.java
package com.atguigu.spring.helloworld;
public class HelloWorld {
private String name;
public void setName2(String name) {
System.out.println("setName:"+name);
this.name = name;
}
public HelloWorld() {
System.out.println("HelloWorld's constructor...");
}
public void hello(){
System.out.println("Hello: " + user);
}
}
2.Main.java
package com.atguigu.spring.helloworld;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
//1. 创建 Spring 的 IOC 容器,appicationContext实际上是接口,ClassPathXmlApplicationContext是接口实现类,该实现类从类路径下加载文件
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("appicationContext.xml");
//2. 从 IOC 容器中获取 bean 的实例
//创建容器时会对bean进行初始化
HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");
// HelloWorld helloWorld1 = ctx.getBean(HelloWorld.class);
//3. 使用 bean,调用方法
helloWorld.hello();
}
}
3.SpringBeanCongfigurationFile配置文件,appicationContext.xml
class:bean全类名,通过反射方式在IOC容器中创建Bean,要求Bean中必须有无参数构造器
id:标识容器中bean.id唯一
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<bean id = "helloWorld" class="com.spring.beans.HelloWorld">
<property name="name2" value = "Spring"></property>
</bean>
</beans>