spring的ioc
在刚开始学习spring的时候肯定都知道spring的两个特点:ioc,aop,控制反转和切面编程,这篇就只说说ioc
ioc是什么:在我们原来的代码中,如果A依赖了B,那么我们会自己在A类中来new B,创建B的实例来使用,是程序主动的去创建依赖,但是我们在使用spring的了之后还会在A中主动的去创建B吗?基本不会,因为创建对象的这个操作从原来的我们来控制变成了spring来管理,这个过程就称为控制反转,ioc并不是一种技术,而是一种编程思想,代码的设计思路
那么这样做的好处是什么?
-
解耦,将对象之间的依赖关系交给spring来处理,避免硬编码导致高度耦合
-
资源的集中易于管理和配置
而spring实现ioc使用的方法是通过DI(依赖注入),当我们大部分的对象都被spring管理后那么spring也需要将我们A中所依赖的B,C,D...都给填充到A中,这个过程是由spring来管理的,我们只需要按照spring的规则声明或指定,那么spring也会帮我们完成依赖的注入
自动注入
了解完spring的基本思想后,来回想一下当时学习spring的入门,有没有说过spring的一个特点就是可以自动注入?
@Component
public class A {
@Autowired
private B b;
}
@Component
public class B {
}
简单的一段代码,将A,B交给spring管理,在A中属性b上添加一个@Autowired
,当我们从spring的容器中取出A后发现属性b居然有值,这个不就是自动注入吗?
我是认为添加@Autowired注解是不算自动注入的,原因如下
1.名词解释
首先,什么叫自动(给翻译翻译什么叫tm的自动),生活中肯定都见过自动门,通过过自动门,当我们靠近的时候门会自动打开,通过后门自动关闭,自动就是指我们不需要手动的去开门/关门,那么这里的自动注入也是,我们不需要去手动的在需要注入的属性上添加一个@Autowired注解
2.官方文档
Spring Framework Documentation
在官方文档的注入方式中,能看到
Dependency injection (DI) is a process whereby objects define their dependencies (that is, the other objects with which they work) only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse (hence the name, Inversion of Control) of the bean itself controlling the instantiation or location of its dependencies on its own by using direct