IOC


1.IOC本质

IOC

IOC


2.HelloSpring

IOC

  • Hello.java:
package com.kakafa.pojo;

public class Hello {
    private String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}

  • beans.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">

<!--使用spring来创建对象,在Spring中这些都称为bean-->

    <bean id="hello" class="com.kakafa.pojo.Hello">
        <property name="str" value="SpringStr"/>
    </bean>

</beans>

IOC


  • test:
import com.kakafa.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {

    public static void main(String[] args) {
        //获取Spring的上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //我们的对象现在都在Spring中管理了。要使用直接到里面取出来就可以了
        Hello hello = (Hello)context.getBean("hello");
        System.out.println(hello.toString());

    }
}

  • 结果:
    IOC

上一篇:01.IOC


下一篇:2. IoC和DI注解开发