Spring框架之了解DI

DI:   Dependency Injection,是指依赖的对象不需要手动调用 setXX 方法去设置,而是通过配置赋值。 

一、属性设置的方法

二、Spring 属性注入方法

①:构造方法的方式的属性注入

  <!--Spring的属性注入的方式  构造方法-->
    <bean id="car" class="com.spring.demo04.Car">
        <constructor-arg name="name" value="电脑"/>
        <constructor-arg name="price" value="8000000"/>
    </bean>

②:Set方法的方式的属性注入................简单类型的属性

<!--Spring属性注入的方式   set方法-->
    <bean id="car2" class="com.spring.demo04.Car2">
        <property name="name" value="奔驰"/>
        <property name="price" value="10000000"/>
    </bean>

 ②.1:Set方法的方式的属性注入................对象类型的属性

  <!--注入对象类型的属性 利用set方法,当然也可以运用构造函数
        value:设置普通类型的值
        ref:设置其他类的id或name ,引用其他的id或值
    -->
    <bean id="employee" class="com.spring.demo04.Employee">
        <property name="name" value="小明"/>
        <property name="car2" ref="car2"/>引用的是上面的car2的实例&ndash;&gt;
    </bean>

②.2、P名称空间的属性注入 :Spring 2.5以后的版本 

<!--
    下面第一行设置标签。我们可以利用它设置新的名称空间,来进行名称空间的属性注入 .beans是默认的标签
     xmlns:p="http://www.springframework.org/schema/p"
-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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">
<!--
      写法:
            普通属性 p:属性名="值"
            对象类型 p:属性名-ref="值"
-->
<bean id="car2" class="com.spring.demo04.Car2" p:name="辣条" p:price="100"></bean>
     <bean id="employee" class="com.spring.demo04.Employee" p:car2-ref="car2" p:name="王五" ></bean>

②.3:SpEL的属性注入: 利用Spring标签的形式

语法:
       #{SpEl}
<!--还可以利用它引用其它类的属性和方法
        先引用该类--> 
<bean id="carInfo" class="com.spring.demo04.CarInfo"></bean>
    <bean id="car2" class="com.spring.demo04.Car2">
        <property name="name" value="#{carInfo.name}"></property>
        <property name="price" value="#{carInfo.calculatorPrice()}"></property>
    </bean>
    <bean id="employee" class="com.spring.demo04.Employee">
        <property name="name" value="#{'小王'}"></property>
        <property name="car2" value="#{car2}"></property>
    </bean>

③:复杂数据类型的注入  list、set、map集合

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值