Spring的学习_____2.IoC 控制反转

1.Ioc (inversion of control)控制反转(是一种思想)。

IoC是一种思想,在此之前程序中使用对象的创建都必须由程序员完成,IoC将对象的创建,保存,以及管理(生命周期)交由Spring来完成,所以Spring也相当于一个容器(存放对象的对象),该过程即为控制反转。

作用:实现了对象间的解耦,大大降低了耦合性,使模块独立。

2.一个小案例:

(使用Idea下的maven来完成此demo)

1.通过依耐导入Jar包(spring web mvc):

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.9.RELEASE</version>
</dependency>

2.实体类的编写:

public class Hello {

    private String name;

    public Hello() {
    }

    public Hello(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void show(){
        System.out.println("Hello,"+name);
    }

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

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">

    <!--bean就是一个java对象,由Spring管理和创建-->
    <bean id="hello" class="com.kuang.pojo.Hello">
        <property name="name" value="Spring"/>
    </bean>

    <!--bean就是一个java对象,由Spring管理和创建-->
    <bean id="hello2" class="com.kuang.pojo.Hello">
        <property name="name" value="WestOS"/>
    </bean>

    <!--// Hello hello2 = new Hello();-->
    <!--// hello2.setName (WestOS)-->

</beans>

4.测试类:

public class HelloTest {
    @Test
    public void test(){

        //解析beans.xml配置文件,生产管理相应的Bean对象;
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        //通过Bean得到这个对象的实体
        Hello hello = (Hello)context.getBean("hello2");

        hello.show();

    }
}

案例总结:

1.在applicationContext.xml中每一个bean都是一个对象实例,由Spring进行创建,保存和管理其生命周期;

2.使用反射的方式创建对象;

3.使用实体的set方法给属性赋值。

4.Ioc创建对象的两种方式:

  方式1:直接用属性名,给属性赋值(本质:先调用实体类的无参构造方法创建一个对象,在调用set方法进行属性的赋值)

 <bean id="user" class="com.kuang.pojo.User">
        <property name="name" value="qinjiang"/>
    </bean>

方法2:使用有参构造方法直接创建对象,并给属性赋值。

 <!--使用构造器的参数下标进行赋值-->
    <bean id="user2" class="com.kuang.pojo.User">
        <constructor-arg index="0" value="kuangshen"/>
        <constructor-arg index="1" value="18"/>
    </bean>

猜你喜欢

转载自www.cnblogs.com/xbfchder/p/11253621.html