1.1 控制反转( Ioc)快速入门

2016-08-03 23:17:56 8,067 3

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

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

ioc1.png

ioc2.png

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

2.2、Spring编程—IOC程序实现

2.2.1建立spring工程(基于maven)

pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.2.6.RELEASE</version>
    </dependency>
    <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
</dependencies>

2.2.2 编写Java类

接口:

public interface HelloService {
    public void sayHello();
}

实现类:

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

2.2.3 编写配置文件

在resource目录下创建applicationContext.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">

    <!-- 配置实用哪个实现类对Service接口进行实例化 -->
    <!-- 配置实现类HelloServiceImpl,定义名称helloService -->
    <bean
            id="helloService"
            class="com.tianshouzhi.spring.HelloServiceImpl">
    </bean>
</beans>

2.2.4 测试

public class HelloServiceTest {
    //传统写法(紧密耦合)
    @Test
    public void traditionalTest(){
        HelloService service = new HelloServiceImpl();
        service.sayHello();
    }

    //使用Spring
    @Test
    public void springTest(){
        // 工厂+反射+配置文件,实例化Service对象
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        //通过工厂根据配置的实例名称获取实例对象
        HelloService service2=(HelloService) context.getBean("helloService");
        service2.sayHello();
    }
}