IDEA创建Spring项目实现IOC

Spring简介

IOC

IOC全称: Inverse of Control, 控制反转,IOC其实不是什么技术,而是一种设计思想。

简要的说就是:原本需要程序去主动new创建的对象,现在反转过来交给spring的容器去创建。

什么是Spring IOC 和DI(最好的讲解)

创建

IDEA创建Spring项目比eclipse简单了很多很多很多很多。

首先打开IDEA,新建project,勾选新建Spring,点击Finish,完成。

IDEA会自动帮你下载需要的依赖。

之后我们创建学生类,写出基本属性。

右键src创建spring的配置文件

在这里我们给创建的实例初始化值

<?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="student_chen" class="Student">
        <property name="age" value="10"/>
        <property name="name" value="chen"/>
        <property name="number" value="01"/>
    </bean>
</beans>

新建一个测试类,实例化对象。

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
  public static void main(String[] args) {
    ApplicationContext app = new ClassPathXmlApplicationContext("bean.xml");
    Student student = (Student) app.getBean("student_chen");
    System.out.println(student.toString());
  }
}

完成。

如果类之间有继承关系,使用ref引用

使用constructor

使用构造器创建对象,上面的方法使用的是setter方法。

<bean id="classes_02" class="Classes">
        <constructor-arg value="02"/>
        <constructor-arg ref="teacher_li"/>
    </bean>

顺序与构造方法中的顺序一致,当然也可以手动指定顺序

<bean id="classes_02" class="Classes">
        <constructor-arg value="02" index="0"/>
        <constructor-arg ref="teacher_li" index="1"/>
    </bean>

使用name指定,感觉比index方便

  <bean id="classes_02" class="Classes">
        <constructor-arg value="02" index="0" name="num"/>
        <constructor-arg ref="teacher_li" index="1" name="teacher"/>
    </bean>

数组属性类型的注入


 <bean id="abcd" class="ABCD">
        <property name="array">
            <array>
                <value>czt</value>
                <value>slh</value>
            </array>
        </property>
        <property name="arrayList">
            <array>
                <value>czt</value>
                <value>slh</value>
            </array>
        </property>
        <property name="map" >
            <map>
            <entry key="chen" value="01"/>
        </map>
        </property>
    </bean>
</beans>
value中的字符串空值,直接写
<null/>
使用构造方法赋值

使用IOC时,类中必须有无参构造方法

构造方法赋值和普通类型的属性方式相同

使用autowire自动注入

  <bean id="teacher" class="Teacher">
        <property name="name" value="li"/>
        <property name="sex" value="女"/>
     </bean>

    <bean id="classes_02" class="Classes" autowire="byName">
      <property name="num" value="02"/>
    </bean>

若类中属性名和Bean的id相同,将会自动注入

发表评论