Spring---依赖注入(DI)

本文介绍了Spring框架中的依赖注入(DI)概念,包括构造器注入、set注入和P命名注入与C命名注入的使用方式。通过实例演示如何在XML配置文件中为对象设置依赖,并探讨了不同类型的注入策略。同时,讲解了Spring Bean的作用域及其在应用中的实际意义。
摘要由CSDN通过智能技术生成

Spring—依赖注入(DI)

我们的征途是星辰大海,而非人间烟尘

image

概念

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

构造器注入

构造器注入

set注入

要求被注入的属性 , 必须有set方法

  1. 测试类
    Adress.java

    package com.qifei.pojo;
    
    public class Address {
        private String address;
    
        public String getAddress() {
            return address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
    
        @Override
        public String toString() {
            return "Address{" +
                    "address='" + address + '\'' +
                    '}';
        }
    }
    

    Student.java

    package com.qifei.pojo;
    
    import java.util.*;
    
    public class Student {
        private  String name;
        private Address address;
        private String[] books;
        private List<String> hobbys;
        private Map<String,String> card;
        private Set<String> games;
        private String wife;
        private Properties info;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Address getAddress() {
            return address;
        }
    
        public void setAddress(Address address) {
            this.address = address;
        }
    
        public String[] getBooks() {
            return books;
        }
    
        public void setBooks(String[] books) {
            this.books = books;
        }
    
        public List<String> getHobbys() {
            return hobbys;
        }
    
        public void setHobbys(List<String> hobbys) {
            this.hobbys = hobbys;
        }
    
        public Map<String, String> getCard() {
            return card;
        }
    
        public void setCard(Map<String, String> card) {
            this.card = card;
        }
    
        public Set<String> getGames() {
            return games;
        }
    
        public void setGames(Set<String> games) {
            this.games = games;
        }
    
        public String getWife() {
            return wife;
        }
    
        public void setWife(String wife) {
            this.wife = wife;
        }
    
        public Properties getInfo() {
            return info;
        }
    
        public void setInfo(Properties info) {
            this.info = info;
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' + "\n"+
                    " address=" + address.toString() + "\n"+
                    " books=" + Arrays.toString(books) + "\n"+
                    " hobbys=" + hobbys + "\n"+
                    " card=" + card + "\n"+
                    " games=" + games + "\n"+
                    " wife='" + wife + '\'' + "\n"+
                    " info=" + info + "\n"+
                    '}'+"\n";
        }
    }
    
  2. 注入

    <?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" class="com.qifei.pojo.Student">
    
            <!--常量注入-->
            <property name="name" value="qifei"/>
            
            <!--引用注入 -->
            <property name="address" ref="address"/>
            
            <!--数组注入-->
            <property name="books">
                <array>
                    <value>平凡的世界</value>
                    <value>复活</value>
                    <value>追风筝的人</value>
                    <value>三体</value>
                </array>
            </property>
            
            <!--Map 注入-->
            <property name="card" >
                <map>
                    <entry key="身份证" value="1234567890"/>
                    <entry key="校园卡" value="2019010201xx"/>
                    <entry key="银行卡" value="15895203"/>
                </map>
            </property>
            
            <!--set 注入-->
            <property name="games">
                <set>
                    <value>刺激战场</value>
                    <value>王者荣耀</value>
                    <value>英雄联盟</value>
                </set>
            </property>
            
            <!--list 注入-->
            <property name="hobbys">
                <list>
                    <value>跑步</value>
                    <value>羽毛球</value>
                    <value>排球</value>
                </list>
            </property>
            <!--props 注入-->
            
            <property name="info">
                <props>
                    <prop key="driver">mysql</prop>
                    <prop key="root">root</prop>
                    <prop key="password">123456</prop>
                </props>
            </property>
            
            <!--null 注入-->
            <property name="wife">
                <null/>
            </property>
            
        </bean>
    
        <bean id="address" class="com.qifei.pojo.Address">
            <property name="address" value="长沙岳麓"/>
        </bean>
    </beans>
    
  3. 测试

    public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            Student student = context.getBean("student", Student.class);
            System.out.println(student.toString());
        }
    
    
  4. image

  5. Collections

    In the <list/>, <set/>, <map/>, and <props/> elements, you set the properties and arguments of the Java Collection types List, Set, Map, and Properties, respectively.

    <bean id="moreComplexObject" class="example.ComplexObject">
            <!-- results in a setAdminEmails(java.util.Properties) call -->
            <property name="adminEmails">
                    <props>
                            <prop key="administrator">administrator@example.org</prop>
                            <prop key="support">support@example.org</prop>
                            <prop key="development">development@example.org</prop>
                    </props>
            </property>
            <!-- results in a setSomeList(java.util.List) call -->
            <property name="someList">
                    <list>
                            <value>a list element followed by a reference</value>
                            <ref bean="myDataSource" />
                    </list>
            </property>
            <!-- results in a setSomeMap(java.util.Map) call -->
            <property name="someMap">
                    <map>
                            <entry key="an entry" value="just some string"/>
                            <entry key ="a ref" value-ref="myDataSource"/>
                    </map>
            </property>
            <!-- results in a setSomeSet(java.util.Set) call -->
            <property name="someSet">
                    <set>
                            <value>just some string</value>
                            <ref bean="myDataSource" />
                    </set>
            </property>
    </bean>
    

    The value of a map key or value, or a set value, can also again be any of the following elements:

    bean | ref | idref | list | set | map | props | value | null
    

    详细的可以参照官方文档:Spring官方文档

    P命名注入

    1. 引入命名空间:xmlns:p="http://www.springframework.org/schema/p
    2. 这里没有有参构造器
    <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">
    
            <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>
    

    C命名注入

    1. 引入命名空间:xmlns:c="http://www.springframework.org/schema/c
    2. 这里有有参构造器
    <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
                    http://www.springframework.org/schema/beans/spring-beans.xsd">
    
            <bean id="bar" class="x.y.Bar"/>
            <bean id="baz" class="x.y.Baz"/>
    
            <!-- traditional declaration -->
            <bean id="foo" class="x.y.Foo">
                    <constructor-arg ref="bar"/>
                    <constructor-arg ref="baz"/>
                    <constructor-arg value="foo@bar.com"/>
            </bean>
    
            <!-- c-namespace declaration -->
            <bean id="foo" class="x.y.Foo" c:bar-ref="bar" c:baz-ref="baz" c:email="foo@bar.com"/>
    
    </beans>
    

    Bean的作用域

    在Spring中,那些组成应用程序的主体及由Spring IoC容器所管理的对象,被称之为bean。简单地讲,bean就是由IoC容器初始化、装配及管理的对象

    范围描述
    singleton(默认)将单个 bean 定义范围限定为每个 Spring IoC 容器的单个对象实例。
    prototype将单个 bean 定义范围限定为任意数量的对象实例。
    request将单个 bean 定义范围限定为单个 HTTP 请求的生命周期;也就是说,每个 HTTP 请求都有自己的 bean 实例,该 bean 实例是在单个 bean 定义的后面创建的。仅在 web-aware Spring 的上下文中有效ApplicationContext
    session将单个 bean 定义范围限定为 HTTP 的生命周期Session。仅在 web-aware Spring 的上下文中有效ApplicationContext
    application将单个 bean 定义范围限定为ServletContext. 仅在 web-aware Spring 的上下文中有效ApplicationContext
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Liknana

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值