Spring 与 IoC 、简单实例

IoC是一个概念,是一种思想不是实现实现方式有多种。比较流行的方式有2种

依赖查找DL Dependency Lookup)、依赖注入DI Dependency Injection)。

依赖注入方式应用更加广泛Spring就是采用的DI方式

1、创建Service接口

public interface ISomeService {
    void doSome();
}

2、实现Service接口

public class SomeServiceImpl implements ISomeService {

    //无参构造函数
    public SomeServiceImpl() {
        System.out.println("执行无参构造函数");
    }

    @Override
    public void doSome() {
        System.out.println("执行doSome()方法");
    }
}
3、创建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
	相当于 SomeServiceImpl myService = new SomeServiceImpl(); -->
    <bean id="myService" class="com.xxx.spring.service.SomeServiceImpl"/>

</beans>
4、测试代码

public class MyTest {

    //传统方式
    @Test
    public void test1() {
        ISomeService service = new SomeServiceImpl();
        service.doSome();
    }

    // spring方式-1
    // 代码中完全没有出现SomeServiceImpl实现类,只知道接口。实现解耦。
    // 以后就算怎么修改SomeServiceImpl实现类,代码都不用动。就算修改类名,只需修改配置
    @Test
    public void test2() {
        //创建容器对象,加载spring配置文件
        //类根目录路径找配置文件
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        ISomeService service = (ISomeService) ac.getBean("myService");
        service.doSome();
    }

    //spring方式-2
    @Test
    public void test3() {
        // 创建容器对象,加载spring配置文件
        // 默认:项目根目录下面找
        // 3-01-spring/applicationContext_file.xml
        // 其实可以放在系统的任意位置 比如D:盘等等
        ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext_file.xml");
        ISomeService service = (ISomeService) ac.getBean("myService");
        service.doSome();
    }

    //spring方式=3
    // ApplicationContext容器和BeanFactory容器的不同【通过debug可以看出】
    // ApplicationContext是接口,继承了BeanFactory。BeanFactory是根接口
    // 这2个容器对于其中Bean的创建时机不同:
    // 1)ApplicationContext容器在进行初始化时,会将其中所有的Bean(对象)进行创建
    //    缺点:占用系统资源(CPU、内存)
    //    优点:响应速度快
    // 2)BeanFactory容器中的对象,在容器初始化时并不会创建,而是在真正获取该对象时才被创建
    //    缺点:相对来说,响应速度慢
    //    优点:不多占用系统资源
    @Test
    public void test4() {
        BeanFactory ac = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
        ISomeService service = (ISomeService) ac.getBean("myService");
        service.doSome();
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值