java之spring之依赖注入


一.DI: Dependency injection; 依赖注入

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

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

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

二.Spring中如何注入属性

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

class="cn.sxt.vo.User">
        
        
    

2.数组的设置


            
                足球
                蓝球
                乒乓球
            
        

3.List 的设置和数组一样


            
                北京昌平
                山西平遥
                xxxx
            
        

或者


            
                北京昌平
                山西平遥
                xxxx
            
        

4. set 集合设置


            
                大话设计模式
                head.first java
            
        

5.Map集合设置


            
                
                    ABC
                
                
            
        

6. Properties注入


            
                60kg
                170cm
            
        

7. 对象的注入


        ref="myRole"/>
    
    myRole" class="cn.sxt.vo.Role">
        
        
    

8. p 命名空间注入

需要导入头文件


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

配置


    class="cn.sxt.vo.Role" p:id="1007" p:name="vip">

9. c命名空间注入

需要导入头文件


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

配置


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

10. Null 注入

class="cn.sxt.vo.Role">
        
        <null/>
    

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

 1.构造器注入

 2. Set方法注入

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

相关