Spring 学习(一)IOC

前言:
IOC:控制反转,当我们需要一个对象时,并不是自己去new一个,而是由外部容易负责创建和维护。举个例子:我们租房的话,一般不是自己一个个的去小区找,而是通过房屋中介来完成,我们只需要缴费即可。

DI:依赖注入,是IOC实现的一种方式

一、一般我们调用类中的某个方法,我们是如何实现的呢
1、先创建一个接口OneInterface,有个方法

public interface OneInterface {
    String hello(String word);
}

2、创建一个实现OneInterface接口的类OnInterfaceImpl

public class OnInterfaceImpl  implements OneInterface{

    @Override
    public String hello(String word) {

        return "hello ----->" + word;
    }

}

3、我们要调用OnInterfaceImpl的hello方法

public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

        //接口中只有方法,没有具体的实现方法,面向接口编程,需要一个接口和一个接口实现类
        OneInterface onInterfaceImpl = new OnInterfaceImpl();
        System.out.println(onInterfaceImpl.hello("哈哈哈"));
    }

二、我们使用spring bean配置
1、新建一个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.yuna.OnInterfaceImpl">

        </bean>
</beans>

2、新建一个测试基类UnitTestBase

public class UnitTestBase {

    private ClassPathXmlApplicationContext  context;

    private String springXmlpath;

    public UnitTestBase() { }

    public UnitTestBase(String springXmlpath) {
        this.springXmlpath = springXmlpath;
    }

    @Before
    public void before() {

        if (StringUtils.isEmpty(springXmlpath)) {
            springXmlpath = "classpath*:spring-*.xml";
        }
        try {
            context =  new ClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+"));
            context.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @After
    public void after() {
        context.destroy();
    }

    @SuppressWarnings("unchecked")
    protected <T extends Object> T getBean(String beanId) {
        try {
            return (T)context.getBean(beanId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    protected < T extends Object> T getBean(Class <T> clazz) {
        try {
            return context.getBean(clazz);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

3、新建一个TestOneInterface测试类继承UnitTestBase

@RunWith(BlockJUnit4ClassRunner.class)
public class TestOneInterface extends UnitTestBase {

    public  TestOneInterface() {
        super("classpath*:spring-ioc.xml");//classpath :相对路径
    }

    @Test
    public void testHello() {
        OneInterface oneInterface = super.getBean("OneInterface");//与“spring-ioc.xml”中的bean id 一致
        System.out.println(oneInterface.hello("您好"));
    }
}

猜你喜欢

转载自blog.csdn.net/ycf03211230/article/details/79433486