二、初学SpringMVC+Mybatis之Spring IOC

来源:互联网 发布:公司取名软件注册码 编辑:程序博客网 时间:2024/05/20 01:46

1、IOC的概念

        IOC全称是Inversionof Control ,译为控制反转。IOC是Spring框架的基础和核心。

        IOC是指程序中对象的获取方式发生反转,由原来我们自己new的方式,变为了spring给我们注入,他降低了对象之间的耦合度。

        DI 全称是DependencyInjiction,译为依赖注入。

        DI的原理就是将一起工作的具有关系的对象,通过构造方法参数或者方法参数传入建立关联,容器的工作就是创建bean时注入这些依赖关系。

        IOC是一种思想,而DI是实现IOC的技术途径。

        DI注入的方式有两种,setter注入和构造器注入。


2、setter注入
        通过调用无参构造器或者无参static工厂方法实例化bean之后,调用该bean的setter方法,即为set注入。

javabean:package pers.zky.entity;import java.io.Serializable;/** * @author Zky * Book类,测试setter注入 */public class Book implements Serializable{    private String id;    private String name;    public Book() {    }    public Book(String id, String name) {        this.id = id;        this.name = name;    }    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}xml:<bean id="book" class="com.tz.entity.Book">    <!-- setter注入 -->    <property name="id" value="A0001"></property>    <property name="name" value="平凡的世界"></property></bean>javatest:package pers.zky.test;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import pers.zky.entity.Book;public class TestDemo {    @Test    public void test() {        String str = "applicationContext.xml";        ApplicationContext ac = new ClassPathXmlApplicationContext(str);        Book book = ac.getBean("book",Book.class);        System.out.println(book.getId());        System.out.println(book.getName());    }}Console:A0001平凡的世界


3、构造器注入

        通过调用有参构造器实例化bean之后,即为构造器注入。同样使用上面的javabean和javatest,在xml中注释掉set注入的语句,加入构造器注入的语句。

xml:<bean id="book1" class="com.tz.entity.Book1">    <!-- 构造器注入,按有参构造方法里参数的顺序 -->    <constructor-arg index="0" value="B0001"></constructor-arg>    <constructor-arg index="1" value="围城"></constructor-arg></bean>Console:B0001围城


4、自动装配

        SpringIoc容器可以自动装配(autowire)相互协作bean之间的关联关系,Autowire可以针对单个bean 进行设置,autowire的方便之处在于减少xml的注入配置。
在xml中,可以在<bean>元素使用autowire属性指定自动装配的规则,一共五种类型值:

        1)、no

        禁用自动装配,默认值。

        2)、byName

        根据属性名自动装配。在容器中寻找与该属性名相同的bean,如果没有找到则为null。

        3)、byType

        根据属类型自动装配。在容器中寻找与该属性类型匹配的bean,如果发现多个将会抛出异常,如果没有找到则为null。

        4)、constructor

        与byType的方式类似,不同之处在于它应用于构造器参数。如果没有找到与构造器参数类型一致的bean将会抛出异常。

        5)、autodetect

        通过bean的类来决定是使用byType还是constructor的方式进行自动装配。如果发现默认的构造器,那么使用byType方式。

0 0