IOC(Inversion of Control),控制反转。
就是指将对象的创建,对象的存储(map),对象的管理(依赖查找,依赖注入)交给了spring容器。
例子如下:
先创建好Maven项目,再在项目中的pom.xml文件引入以下依赖:
<!-- 集中定义依赖版本号 -->
<properties>
<junit.version>4.10</junit.version>
<spring.version>4.1.3.RELEASE</spring.version>
</properties>
<dependencies>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
插入依赖后在项目里创建一个pojo包后就随便创建一个对象并在对象里写一些属性。
然后就在src里的resource里面创建xml文件,具体要创建的文件如下所示:
创建完该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-4.0.xsd">
<bean id="hello" class="com.lingnan.pojo.Hello"></bean>
</beans>
其中,id是这个bean的唯一表示,而class则是对象在项目里面的位置
然后我们就可以写一个测试类进行测试了。
测试类的核心代码为:
ClassPathXmlApplicationContext ac =new ClassPathXmlApplicationContext(“application.xml”);
Hello h = ac.getBean(“hello”);
System.out.println(h);
这样我们就完成了IOC控制反转的展示了。