java之spring之依赖注入

本文内容纲要:java之spring之依赖注入

一.DI: Dependency injection; 依赖注入

依赖注入和控制反转是同一个概念的不同说法。

对象的创建依赖于容器。对象属性的设置是由容器来设置。

对象属性的赋值过程称为注入。

二.Spring中如何注入属性:

1.普通属性(String 和 基本数据类型),直接通过 property 设置即可

<bean id="user" class="cn.sxt.vo.User">

<property name="name" value="张三疯"/>

<property name="age" value="22"/>

</bean>

2.数组的设置

<property name="hobbies">

<array>

<value>足球</value>

<value>蓝球</value>

<value>乒乓球</value>

</array>

</property>

3.List 的设置和数组一样

<property name="addreess">

<list>

<value>北京昌平</value>

<value>山西平遥</value>

<value>xxxx</value>

</list>

</property>

或者

<property name="addreess">

<array>

<value>北京昌平</value>

<value>山西平遥</value>

<value>xxxx</value>

</array>

</property>

  1. set 集合设置

    大话设计模式

    head.first java

5.Map集合设置

<property name="cards">

<map>

<entry key="农业银行">

<value>ABC</value>

</entry>

<entry key="工商银行" value="ICBC"/>

</map>

</property>

  1. Properties注入

    60kg

    170cm

  2. 对象的注入

         <property name="role" ref="myRole"/>

    </bean>

    <bean id="myRole" class="cn.sxt.vo.Role">

    <property name="id" value="1001"/>

    <property name="name" value="管理员"/>

    </bean>

  3. p 命名空间注入

需要导入头文件

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:p="http://www.springframework.org/schema/p"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd">

配置

<!-- p-property命名空间的注入 本质是属性,需要为属性提供set方法,只是将属性写bean的属性中 -->

<bean id="r1" class="cn.sxt.vo.Role" p:id="1007" p:name="vip"></bean>

  1. c命名空间注入

需要导入头文件

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:p="http://www.springframework.org/schema/p"

xmlns:c="http://www.springframework.org/schema/c"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd">

配置

<!-- c-constructor命名空间注入 本质是有参构造方法注入,需要提供对应有参构造方法 -->

<bean id="r2" class="cn.sxt.vo.Role" c:id="1006" c:name="普通会员"></bean>

  1. Null 注入

总结:在 spring 中,属性的注入大体上分为两类;

1.构造器注入

  1. Set方法注入

需要注意的是:使用构造器注入时,需要提供对应的构造方法;使用 set 方法注入时,需要提供对应的 set 方法。

本文内容总结:java之spring之依赖注入

原文链接:https://www.cnblogs.com/Vincent-yuan/p/11247831.html

以上是 java之spring之依赖注入 的全部内容, 来源链接: utcz.com/z/295807.html

回到顶部