依赖注入(Dependency Injection,DI)

依赖注入(Dependency Injection,DI)

  • 依赖注入(Dependency Injection,DI)。
  • 依赖 : 指Bean对象的创建依赖于容器 . Bean对象的依赖资源 .
  • 注入 : 指Bean对象所依赖的资源 , 由容器来设置和装配 .

构造器注入

可以看上一篇文章的讲解通过无参构造方法和有参构造方法实现的注入

Set 注入

要求被注入的属性 , 必须有set方法 , set方法的方法名由set + 属性首字母大写 , 如果属性是boolean类型 , 没有set方法 , 是 is .
实体类:

 public class Address {
 
     private String address;
 
     public String getAddress() {
         return address;
    }
 
     public void setAddress(String address) {
         this.address = address;
    }
 }
public class User {

        private String name;
        private Address address;
        private String[] books;
        private List<String> hobbys;
        private Map<String,String> card;
        private Set<String> games;
        private String test;
        private Properties info;

        public void setName(String name) {
            this.name = name;
        }

        public void setAddress(Address address) {
            this.address = address;
        }

        public void setBooks(String[] books) {
            this.books = books;
        }

        public void setHobbys(List<String> hobbys) {
            this.hobbys = hobbys;
        }

        public void setCard(Map<String, String> card) {
            this.card = card;
        }

        public void setGames(Set<String> games) {
            this.games = games;
        }

        public void setTest(String test) {
            this.test = test;
        }

        public void setInfo(Properties info) {
            this.info = info;
        }

        public void show(){
            System.out.println("name="+ name
                    + ",address="+ address.getAddress()
                    + ",books="
            );
            for (String book:books){
                System.out.print("<<"+book+">>\t");
            }
            System.out.println("爱好:"+hobbys);

            System.out.println("card:"+card);

            System.out.println("games:"+games);

            System.out.println("test:"+test);

            System.out.println("info:"+info);

        }

1、常量注入

<bean id="user" class="cn.domain.User">
     <property name="name" value="Daylight"/>
 </bean>

2、Bean注入

  
 <bean id="addr" class="cn.domain.Address">
     <property name="address" value="中国"/>
 </bean>
  <!--这里的值是一个引用,ref-->
 <bean id="user" class="cn.domain.User">
     <property name="name" value="Daylight"/>
     <property name="address" ref="addr"/>
 </bean>

3、数组注入

 <bean id="user" class="cn.domain.User">
     <property name="name" value="Daylight"/>
     <property name="address" ref="addr"/>
     <property name="books">
         <array>
             <value>Java入门</value>
             <value>删库跑路</value>
             <value>Mysql</value>
         </array>
     </property>
 </bean>

4、List注入

 <property name="hobbys">
     <list>
         <value>听歌</value>
         <value>看电影</value>
         <value>爬山</value>
     </list>
 </property>

5、Map注入

 <property name="card">
     <map>
         <entry key="农行" value="4566767676676"/>
         <entry key="建设" value="1456565657561"/>
     </map>
 </property>

6、set注入

 <property name="games">
     <set>
         <value>秦时明月</value>
         <value>海贼王</value>
         <value>火影忍者</value>
     </set>
 </property>

7、Null注入

 <property name="test"><null/></property>

8、Properties注入

<property name="info">
     <props>
         <prop key="年龄">20</prop>
         <prop key="性别"></prop>
         <prop key="姓名">Daylight</prop>
     </props>
 </property>

9、p命名和c命名注入
p-namespace允许您使用bean元素的属性(而不是嵌套的 元素)来描述协作Bean的属性值,或同时使用这两者。
与具有p-namespace的XML Shortcut相似,在Spring 3.1中引入的c-namespace允许使用内联属性来配置构造函数参数,而不是嵌套constructor-arg元素。
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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean name="classic" class="com.example.ExampleBean">
        <property name="email" value="someone@somewhere.com"/>
    </bean>

    <bean name="p-namespace" class="com.example.ExampleBean"
        p:email="someone@somewhere.com"/>
</beans>
<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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean name="john-classic" class="com.example.Person">
        <property name="name" value="John Doe"/>
        <property name="spouse" ref="jane"/>
    </bean>

    <bean name="john-modern"
        class="com.example.Person"
        p:name="John Doe"
        p:spouse-ref="jane"/>

    <bean name="jane" class="com.example.Person">
        <property name="name" value="Jane Doe"/>
    </bean>
</beans>

此示例不仅包括使用p-namespace的属性值,而且还使用特殊格式来声明属性引用。第一个bean定义用于创建从beanjohn到bean的引用 jane,而第二个bean定义p:spouse-ref="jane"用作属性来执行完全相同的操作。在这种情况下,spouse属性名称是,而该-ref部分表示这不是一个直接值,而是对另一个bean的引用。
P命名空间注入 : 需要在头文件中加入约束文件

导入约束 : xmlns:p="http://www.springframework.org/schema/p"

 <bean id="user" class="cn.domain.User" p:name="Daylight" p:age="20"/>

c 命名空间注入
注意:c:名称空间执行与 基于构造函数的依赖注入相同的操作,没有构造函数会报错

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:c="http://www.springframework.org/schema/c"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="beanTwo" class="x.y.ThingTwo"/>
    <bean id="beanThree" class="x.y.ThingThree"/>

    <!-- traditional declaration with optional argument names -->
    <bean id="beanOne" class="x.y.ThingOne">
        <constructor-arg name="thingTwo" ref="beanTwo"/>
        <constructor-arg name="thingThree" ref="beanThree"/>
        <constructor-arg name="email" value="something@somewhere.com"/>
    </bean>

    <!-- c-namespace declaration with argument names -->
    <bean id="beanOne" class="x.y.ThingOne" c:thingTwo-ref="beanTwo"
        c:thingThree-ref="beanThree" c:email="something@somewhere.com"/>

</beans>

c命名空间注入 : 需要在头文件中加入约束文件

导入约束 : xmlns:c="http://www.springframework.org/schema/c"

 <!--C(构造: Constructor)命名空间 , 属性依然要设置set方法-->
 <bean id="user" class="com.kuang.pojo.User" c:name="Daylight" c:age="20"/>

该c:命名空间使用相同的约定作为p:一个(尾部-ref的bean引用),供他们的名字设置构造函数的参数。同样,即使未在XSD模式中定义它(也存在于Spring内核中),也需要在XML文件中声明它。
对于极少数情况下无法使用构造函数参数名称的情况(通常,如果字节码是在没有调试信息的情况下编译的),则可以对参数索引使用后备,如下所示:

<!-- c-namespace index declaration -->
<bean id="beanOne" class="x.y.ThingOne" c:_0-ref="beanTwo" c:_1-ref="beanThree"
    c:_2="something@somewhere.com"/>

Bean的作用域
在这里插入图片描述
几种作用域中,request、session作用域仅在基于web的应用中使用(不必关心你所采用的是什么web应用框架),只能用在基于web的Spring ApplicationContext环境。

Singleton
在这里插入图片描述

当一个bean的作用域为Singleton,那么Spring IoC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例。Singleton是单例类型,就是在创建起容器时就同时自动创建了一个bean的对象,不管你是否使用,他都存在了,每次获取到的对象都是同一个对象。注意,Singleton作用域是Spring中的缺省作用域。要在XML中将bean定义成singleton,可以这样配置:

 <bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" scope="singleton">

Prototype
在这里插入图片描述

当一个bean的作用域为Prototype,表示一个bean定义对应多个对象实例。Prototype作用域的bean会导致在每次对该bean请求(将其注入到另一个bean中,或者以程序的方式调用容器的getBean()方法)时都会创建一个新的bean实例。Prototype是原型类型,它在我们创建容器的时候并没有实例化,而是当我们获取bean的时候才会去创建一个对象,而且我们每次获取到的对象都不是同一个对象。根据经验,对有状态的bean应该使用prototype作用域,而对无状态的bean则应该使用singleton作用域。在XML中将bean定义成prototype,可以这样配置:

 <bean id="account" class="com.foo.DefaultAccount" scope="prototype"/>  

或者

 <bean id="account" class="com.foo.DefaultAccount" singleton="false"/>

Request
当一个bean的作用域为Request,表示在一次HTTP请求中,一个bean定义对应一个实例;即每个HTTP请求都会有各自的bean实例,它们依据某个bean定义创建而成。该作用域仅在基于web的Spring ApplicationContext情形下有效。考虑下面bean定义:

 <bean id="loginAction" class=cn.csdn.LoginAction" scope="request"/>

针对每次HTTP请求,Spring容器会根据loginAction bean的定义创建一个全新的LoginAction bean实例,且该loginAction bean实例仅在当前HTTP request内有效,因此可以根据需要放心的更改所建实例的内部状态,而其他请求中根据loginAction bean定义创建的实例,将不会看到这些特定于某个请求的状态变化。当处理请求结束,request作用域的bean实例将被销毁。

Session
当一个bean的作用域为Session,表示在一个HTTP Session中,一个bean定义对应一个实例。该作用域仅在基于web的Spring ApplicationContext情形下有效。考虑下面bean定义:

 <bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>

针对某个HTTP Session,Spring容器会根据userPreferences bean定义创建一个全新的userPreferences bean实例,且该userPreferences bean仅在当前HTTP Session内有效。与request作用域一样,可以根据需要放心的更改所创建实例的内部状态,而别的HTTP Session中根据userPreferences创建的实例,将不会看到这些特定于某个HTTP Session的状态变化。当HTTP Session最终被废弃的时候,在该HTTP Session作用域内的bean也会被废弃掉。
在这里插入图片描述

posted @ 2021-02-05 00:23  Latteitcjz  阅读(120)  评论(0)    收藏  举报