-->

spring学习:控制反转( Ioc)急速入门,看图理解【云图智联】

2020-08-15 05:14发布

2.1 什么是控制反转(IOC:Inverse of Control)

IOC反转控制,实际上就是将对象的创建权交给了Spring,程序员无需自己手动实例化对象。

可以看出来工厂的作用就是用来解耦合的,而在使用spring的过程中,spring就是充当这个工厂的角色。IOC反转控制,实际上就是将对象的创建权交给了Spring,程序员无需自己手动实例化对象

2.2、Spring编程—IOC程序实现

2.2.1建立spring工程(基于maven)

pom.xml

  1. <dependencies>
  2.     <dependency>
  3.         <groupId>org.springframework</groupId>
  4.         <artifactId>spring-context</artifactId>
  5.         <version>4.2.6.RELEASE</version>
  6.     </dependency>
  7.     <dependency>
  8.             <groupId>junit</groupId>
  9.             <artifactId>junit</artifactId>
  10.             <version>4.12</version>
  11.         </dependency>
  12. </dependencies>

2.2.2 编写Java类

接口:

  1. public interface HelloService {
  2.     public void sayHello();
  3. }

实现类:

  1. public class HelloServiceImpl implements HelloService {
  2.     public void sayHello(){
  3.         System.out.println("hello,spring");
  4.     }
  5. }

2.2.3 编写配置文件

在resource目录下创建applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- 引入约束 -->
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5.        xsi:schemaLocation="
  6. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  7.  
  8.     <!-- 配置实用哪个实现类对Service接口进行实例化 -->
  9.     <!-- 配置实现类HelloServiceImpl,定义名称helloService -->
  10.     <bean
  11.             id="helloService"
  12.             class="com.tianshouzhi.spring.HelloServiceImpl">
  13.     </bean>
  14. </beans>

2.2.4 测试

  1. public class HelloServiceTest {
  2.     //传统写法(紧密耦合)
  3.     @Test
  4.     public void traditionalTest(){
  5.         HelloService service = new HelloServiceImpl();
  6.         service.sayHello();
  7.     }
  8.  
  9.     //使用Spring
  10.     @Test
  11.     public void springTest(){
  12.         // 工厂+反射+配置文件,实例化Service对象
  13.         ApplicationContext context = new ClassPathXmlApplicationContext(
  14.                 "applicationContext.xml");
  15.         //通过工厂根据配置的实例名称获取实例对象
  16.         HelloService service2=(HelloService) context.getBean("helloService");
  17.         service2.sayHello();
  18.     }
  19. }

免费学习视频欢迎关注云图智联:https://e.yuntuzhilian.com/ 

标签: