Spring IOC/DI
一 IOC和DI是什么
IOC即控制反转,最浅显的回答就是是对象的创建不用手动去new,而是让Spring去完成对象的创建;
IOC:控制反转也叫依赖注入,IOC利用java反射机制,AOP利用代理模式。所谓控制反转是指,本来被调用者的实例是由调用者来创建的,这样的缺点是耦合性太强,IOC则是统一交给spring来管理创建,将对象交给容器管理,你只需要在spring配置文件总配置相应的bean,以及设置相关的属性,让spring容器来生成类的实例对象以及管理对象。在spring容器启动的时候,spring会把你在配置文件中配置的bean都初始化好,然后在你需要调用的时候,就把它已经初始化好的那些bean分配给你需要调用这些bean的类。
DI即依赖注入,意思是Spring主动创建被调用类的对象,然后把这个对象注入到我们自己的类中,让我们能够使用它。
实现IOC的简单例子(XML和注解两种方式)
XML实现方式
1.首先创建一个maven项目,引入如下两个依赖:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
spring-context包下的ApplicationContext接口是SpringFramework中Bean的管理者,为SpringFramework的诸多功能提供支撑作用。
2.创建一个实体类Person
@Repository
public class Person {
private String name;
private int age;
//getter and setter...
}
@Repository注解用于标注数据访问组件,即DAO组件
3.创建配置文件ApplicationContext.xml(官方推荐命名,我这里用的是beans.xml)
<?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">
<bean id="person" class="com.ikun.cap1.entity.Person">
<property name="name" value="lmx"/>
<property name="age" value="189"/>
</bean>
</beans>
4.创建测试类
/**
* beans.xml方式初始化bean 构造注入 setter注入
* @author Admin
*
*/
public class MainTest1 {
public static void main(String[] args) {
//读取xml并实例化容器
ApplicationContext app = new ClassPathXmlApplicationContext("beans.xml");
Person person = app.getBean("person", Person.class);
System.out.println(person.toString());
}
}
运行结果:
Person [name=lmx, age=189]
注解实现方式
1.添加config配置
@Configurable
public class MainConfig {
@Bean(name="per")//不配置name属性, 默认名为方法名person2
public Person person2() {
return new Person("银临", 19);
}
}
2.修改main方法中的配置
public static void main(String[] args) {
ApplicationContext app = new AnnotationConfigApplicationContext(MainConfig.class);
String[] beanNamesForType = app.getBeanNamesForType(Person.class);
for (String beanName : beanNamesForType) {
System.out.println(beanName);
Person person = app.getBean(beanName, Person.class);
System.out.println(person.toString());
}
}
运行结果:
per
Person [name=银临, age=19]