Spring:Spring 指的是 Spring Framework(Spring 框架),是⼀个开源框架它可以让 Java 企业级的应⽤程序开发起来更简单。
理解控制反转:
代码实现:
public class NewCarExample { public static void main(String[] args) { Car car = new Car(); car.init(); } /** * 汽⻋对象 */ static class Car { public void init() { // 依赖⻋身 Framework framework = new Framework(); framework.init(); } } /** * ⻋身类 */ static class Framework { public void init() { // 依赖底盘 Bottom bottom = new Bottom(); bottom.init(); } } /** * 底盘类 */ static class Bottom { public void init() { // 依赖轮胎 Tire tire = new Tire(); tire.init(); } } /** * 轮胎类 */ static class Tire { // 尺⼨ private int size = 30; public void init() { System.out.println("轮胎尺⼨:" + size); } } }
问题:
解决办法:
改进代码:
public class IocCarExample { public static void main(String[] args) { Tire tire = new Tire(20); Bottom bottom = new Bottom(tire); Framework framework = new Framework(bottom); Car car = new Car(framework); car.run(); } static class Car { private Framework framework; public Car(Framework framework) { this.framework = framework; } public void run() { framework.init(); } } static class Framework { private Bottom bottom; public Framework(Bottom bottom) { this.bottom = bottom; } public void init() { bottom.init(); } } static class Bottom { private Tire tire; public Bottom(Tire tire) { this.tire = tire; } public void init() { tire.init(); } } static class Tire { private int size; public Tire(int size) { this.size = size; } public void init() { System.out.println("轮胎:" + size); } } }
![]()
Spring的核心功能:存对象和取对象
DI:Dependency Injection(依赖注入)