Spring

控制反转

类的定义

1
2
3
4
5
6
7
8
package cn.studybigdata.javaee.spring.ioc;

public class Computer {

public void surf(){
System.out.println("电脑上网");
}
}

传统方式创建类的实例

1
2
Computer thinkpad = new Computer();
thinkpad.surf();

IOC方式创建类的实例

配置实例
1
<bean id="computer" class="cn.studybigdata.javaee.spring.ioc.Computer"/>
获取实例
1
2
3
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-cfg.xml");
Computer huawei =(Computer) ac.getBean("computer");
huawei.surf();

这种方式有个优点,如果需要换一种上网设备,如Mobile,只需要让Mobile继承Computer类;在配置实例时,指定classMobile的全限定类名即可。编译时类为Computer,运行时类型为Mobile,多态发生。

声明该变量的类型为编译时类型

赋值给该变量的类型为运行时类型

依赖注入

Setter

Computer
1
2
3
4
5
6
public class Computer {

public void surf(){
System.out.println("电脑上网");
}
}
Human
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Human {

private Computer computer;

//setter
public void setComputer(Computer computer) {
this.computer = computer;
}

public void useComputer(){
computer.surf();
}
}
传统方式
1
2
3
4
Computer computer = new Computer();
Human human = new Human();
human.setComputer(computer);
human.useComputer();
Spring依赖注入
1
2
3
4
5
<bean id="computer" class="cn.studybigdata.javaee.spring.ioc.Computer"/>

<bean id="human" class="cn.studybigdata.javaee.spring.ioc.Human">
<property name="computer" ref="computer"/>
</bean>

构造函数

Computer
1
2
3
4
5
6
public class Computer {

public void surf(){
System.out.println("电脑上网");
}
}
Human
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Human {

private Computer computer;

//构造函数
public Human(Computer computer) {
this.computer = computer;
}

public void useComputer(){
computer.surf();
}
}

在这里,定义了一个包含一个参数的构造函数,只能使用该构造函数实例化对象,无法使用无参构造函数实例化对象。即new Human()创建一个对象。

传统方式
1
2
3
Computer computer = new Computer();
Human human = new Human(computer); //new Human()会报错
human.useComputer();
依赖注入
1
2
3
4
5
<bean id="computer" class="cn.studybigdata.javaee.spring.ioc.Computer"/>

<bean id="human" class="cn.studybigdata.javaee.spring.ioc.Human">
<constructor-arg index="0" ref="computer"/>
</bean>

注意:使用Spring依赖注入的方式,需要指定默认无参构造函数。