二、Spring 入门IOC之前奏 用IOC替换接口编程

1、编写一个接口,创建一个TestInjection.java文件

package com.imooc.ioc.interfaces;

public interface OneInterface {
	
	public void say(String arg);
	
}

2,编写一个实现类,创建一个OneInterfaceImpl.java文件。

package com.imooc.ioc.interfaces;

public class OneInterfaceImpl implements OneInterface {
	
	public void say(String arg) {
		System.out.println("ServiceImpl say: " + arg);
	}

}

3,使用将实现类交给Spring,在resource文件夹下创建spring-ioc.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" >
        
	<bean id="oneInterface" class="com.imooc.ioc.interfaces.OneInterfaceImpl"></bean>
	
 </beans>

4,编写一个测试类,在test文件夹下创建一个TestOneInterface.java文件。

package com.imooc.test.ioc.interfaces;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
//import org.springframework.test.context.ContextConfiguration;
//import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.imooc.ioc.interfaces.OneInterface;
import com.imooc.test.base.UnitTestBase;

//子类具体执行单元测试的类加注解
@RunWith(BlockJUnit4ClassRunner.class)
public class TestOneInterface  {
	//原生的IOC容器
	@Test 
	public void testSourceIOC() {
		//1、将配置文件在资源文件xml文件中配置,将POJO对象交给Spring 容器
		
		//2、从Spring容器中获取Bean,也就是对象
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-ioc.xml");
		
		//3、启动Spring容器
		context.start();
		
		//4、用一个对象类来接收由Spring创建出来的对象
		OneInterface oneInterface =(OneInterface) context.getBean("oneInterface");
		
		//5、使用Spring创建出来的对象
		oneInterface.say("ceshi");
		
		//6、使用完成后销毁对象
		context.destroy();
	}

}

5,查看运行结果

Jul 09, 2018 8:41:03 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh

信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@36aa7bc2: startup date [Mon Jul 09 20:41:03 CST 2018]; root of context hierarchy

Jul 09, 2018 8:41:03 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

信息: Loading XML bean definitions from class path resource [spring-ioc.xml]

ServiceImpl say: ceshi

Jul 09, 2018 8:41:03 PM org.springframework.context.support.AbstractApplicationContext doClose

信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@36aa7bc2: startup date [Mon Jul 09 20:41:03 CST 2018]; root of context hierarchy






猜你喜欢

转载自blog.csdn.net/weixin_39527812/article/details/80976973