IoC(Inverse of Control),控制反转,简单的解释:在传统的开发模式下,我们都是采用直接 new 一个对象的方式来创建对象,也就是说你的对象直接由你自己控制,但是有了 IOC 容器后,则直接由 IoC 容器来控制。需要实例对象时,从spring工厂(容器)中获得,需要将实现类的全限定名称配置到xml文件中。
来一个超简单的例子加以说明:
(1)首先导入jar包:四个核心(bean,core,context,expression),一个依赖(commons-loggings)
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.8.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
(2)简单提供一个接口和一个接口的实现类:
接口:
public interface UserService {
public void addUser();
}
实现类:
public class UserServiceImpl implements UserService {
public void addUser() {
System.out.println("IoC demo");
}
}
(3)添加xml配置文件applicationContext:
<?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">
<!-- 配置service
<bean>配置需要创建的对象
<id>用于之后从spring容器中获得实例时使用的
<class>需要创建实例的全限定类名 -->
<bean id="userServiceId" class="com.lyc.ioc.UserServiceImpl">
</bean>
</beans>
(4)测试类进行测试:
public class TestIoc {
//以前的做法:
@Test
public void demo01(){
UserService userService = new UserServiceImpl();
userService.addUser();
}
//有了IoC之后:
@Test
public void demo02(){
//从spring容器获得
String xmlPath = "main/resources/applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserService userService = (UserService)applicationContext.getBean("userServiceId");
userService.addUser();
}
}