作为即将毕业的大四老油条,写点笔记,帮助记忆,如果有小伙伴发现有误的地方,希望可以留言,不胜感激。
一、IoC 依赖注入/控制反转
IoC :Inversion of COntrol
它不是什么新的技术,而是一种设计理念。在我们学习 编程语言 的过程中也遇到过很多,而且在Java开发的过程中,如果能够较好的使用IoC的设计理念,那将会对开发的性能有很棒的改观。
谁控制谁?控制什么?
答:IoC容器控制对象,控制外部资源的获取
何为反转?哪些方面反转了?
答:容器主动注入对象,对象被动的接受依赖(以往都是在使用对象的时候,先new出一块内存空间,现在不需要了 只需要在对象添加注解 @Autowired ,就实现其new的对象的功能),所以是反转了。依赖对象的获取被反转了。
第一种:
public class Ioc {
public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();
//依赖注入
parent.getChild(child);
}
}
class Parent{
public void getChild(Child child) {
System.out.println("child 对象注入。。。");
}
}
class Child{
}
第二种:spring IoC
使用第二种方法,最主要的还是配置bean节点,既可以在xml中添加,也可以使用注解的方式添加:
1)springMVC-servlet.xml 中添加bean节点
<bean name="Parent" class="com.spring.service.Parent"></bean>
<bean name="Child" class="com.spring.service.Child"></bean>
2)在类的上方添加注解
@Component
public class Parent {}
@Component
public class Child {}
@Component
public class Ioc {}
code如下:
Parent.java
import org.springframework.stereotype.Component;
@Component
public class Parent {
public void getChild(Child child) {
System.out.println("child 对象注入。。。");
}
}
Child.java
import org.springframework.stereotype.Component;
@Component
public class Child {
}
Ioc.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Ioc {
@Autowired
Parent parent;
@Autowired
Child child;
void test() {
//依赖注入
parent.getChild(child);
}
}
Test.java
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("springMVC-servlet.xml");
Ioc ioc =ctx.getBean(Ioc.class);
ioc.test();
}
}
运行结果:
这就是依赖注入/控制反转。