6、Spring之依赖注入

6、依赖注入

6.1、构造器注入

前面已经说过了

6.2、Set方式注入【重点】

  • 依赖注入:Set注入
    • 依赖:bean对象的创建依赖于容器
    • 注入:bean对象中的所有属性,由容器来注入

【环境搭建】

1.复杂类型

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

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

2.真实测试对象

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;

    //... set/get/toString
     
}

3.beans.xml

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="student" class="com.gongyi.pojo.Student">
        <!--第一种,普通值注入,value-->
        <property name="name" value="工一"/>
    </bean>
</beans>

4.测试类:

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

完善注入信息

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="address" class="com.gongyi.pojo.Address">
        <property name="address" value="北京"/>
    </bean>
    <bean id="student" class="com.gongyi.pojo.Student">
        <!--第一种,普通值注入,value-->
        <property name="name" value="工一"/>
        <!--第二种,Bean注入,ref-->
        <property name="address" ref="address"/>
        <!--数组-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
                <value>水浒传</value>
                <value>三国演义</value>
            </array>
        </property>
        <!--List-->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>敲代码</value>
                <value>看电影</value>
            </list>
        </property>

        <!-- Map-->
        <property name="card">
            <map>
                <entry key="身份证" value="123456"/>
                <entry key="银行卡" value="123456"/>
            </map>
        </property>

        <!--Set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>BOB</value>
            </set>
        </property>

        <!--null-->
        <property name="wife">
            <null/>
        </property>

        <!--Properties-->
        <property name="info">
            <props>
                <prop key="dirver">123456</prop>
                <prop key="url"></prop>
                <prop key="username">gongyi</prop>
                <prop key="password">123456</prop>
            </props>
        </property>
    </bean>
</beans>


6.3、拓展方式注入

我们可以使用p命名空间和c命名空间进行注入

官方解释:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4xJfW81F-1641208610807)(D:\study\学习笔记\spring学习\6、依赖注入.assets\image-20220103184546547.png)]

使用:

<?xml version="1.0" encoding="UTF-8"?>
<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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--p命名空间注入,可以直接注入属性的值:properties-->
   <bean id="user" class="com.gongyi.pojo.User" p:name="工一" p:age="22"/>

    <!--c命名空间注入,通过构造器注入:construct-args-->
    <bean id="user2" class="com.gongyi.pojo.User" c:name="木子" c:age="22"/>
</beans>


在父模块引入junit包依赖:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

测试:

@Test
public void test2() {
    ApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml");
    User user = context.getBean("user2", User.class);
    System.out.println(user);

}

注意点:p命名空间和c命名空间不能直接使用,需要导入xml约束

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

6.4、bean的作用域

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-htUftiQs-1641208610810)(D:\study\学习笔记\spring学习\6、依赖注入.assets\image-20220103190824072.png)]

1.单例模式(Spring默认机制)

<bean id="user2" class="com.gongyi.pojo.User" c:name="木子" c:age="22" scope="singleton"/>

官网解释:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CdhsdAlZ-1641208610810)(D:\study\学习笔记\spring学习\6、依赖注入.assets\image-20220103191305737.png)]

2.原型模式:每次从容器中get的时候,都会产生一个新对象

<bean id="user3" class="com.gongyi.pojo.User" c:name="木子" c:age="22" scope="prototype"/>

官网解释:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KMzITTDt-1641208610811)(D:\study\学习笔记\spring学习\6、依赖注入.assets\image-20220103191316209.png)]

3.其余的request,session,application,这些只能在web开发中使用到

代码show

代码结构图:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4ydEuCzC-1641208610812)(D:\study\学习笔记\spring学习\6、依赖注入.assets\image-20220103191342504.png)]

1.新建模块:spring-04-di

2.新建pojo包及类

Address.java

public class Address {
    private String address;
    //set/get/toString
}

Student.java

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;
    //set/get/toString
}

User.java

public class User {
    private String name;
    private int age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
    //set/get/toString
}

3.新建资源文件:

beans.xml

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="address" class="com.gongyi.pojo.Address">
        <property name="address" value="北京"/>
    </bean>
    <bean id="student" class="com.gongyi.pojo.Student">
        <!--第一种,普通值注入,value-->
        <property name="name" value="工一"/>
        <!--第二种,Bean注入,ref-->
        <property name="address" ref="address"/>
        <!--数组-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
                <value>水浒传</value>
                <value>三国演义</value>
            </array>
        </property>
        <!--List-->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>敲代码</value>
                <value>看电影</value>
            </list>
        </property>

        <!-- Map-->
        <property name="card">
            <map>
                <entry key="身份证" value="123456"/>
                <entry key="银行卡" value="123456"/>
            </map>
        </property>

        <!--Set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>BOB</value>
            </set>
        </property>

        <!--null-->
        <property name="wife">
            <null/>
        </property>

        <!--Properties-->
        <property name="info">
            <props>
                <prop key="dirver">123456</prop>
                <prop key="url"></prop>
                <prop key="username">gongyi</prop>
                <prop key="password">123456</prop>
            </props>
        </property>
    </bean>
</beans>


userbean.xml

<?xml version="1.0" encoding="UTF-8"?>
<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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--p命名空间注入,可以直接注入属性的值:properties-->
   <bean id="user" class="com.gongyi.pojo.User" p:name="工一" p:age="22"/>

    <!--c命名空间注入,通过构造器注入:construct-args-->
    <bean id="user2" class="com.gongyi.pojo.User" c:name="木子" c:age="22" scope="singleton"/>

    <bean id="user3" class="com.gongyi.pojo.User" c:name="木子" c:age="22" scope="prototype"/>
</beans>


4.新建测试类:

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.getName());
        System.out.println(student.getAddress());
        System.out.println(student);
        System.out.println(student.toString());
        /**
         * Student{
         * name='工一',
         * address=Address{address='北京'},
         * books=[红楼梦, 西游记, 水浒传, 三国演义],
         * hobbys=[听歌, 敲代码, 看电影],
         * card={身份证=123456, 银行卡=123456},
         * games=[LOL, COC, BOB], wife='null',
         * info={password=123456, dirver=123456, url=男, username=gongyi}
         * }
         */
    }

    @Test
    public void test2() {
        ApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml");
        User user = context.getBean("user2", User.class);
        System.out.println(user);
        User user2 = context.getBean("user2", User.class);
        System.out.println(user==user2);

        User user3 = context.getBean("user3", User.class);
        User user4 = context.getBean("user3", User.class);
        System.out.println(user3==user4);
        System.out.println(user3.hashCode());
        System.out.println(user4.hashCode());

    }


}

彩蛋

1.CPX输入自动提示:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Pdrm6hb5-1641208610813)(D:\study\学习笔记\spring学习\6、依赖注入.assets\image-20220103181219238.png)]

2.依赖注入相关官方文档地址

3.idea同时看两个文件(左右对比)

在这里插入图片描述

4.查看properties子标签

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-I89ZuS85-1641208610816)(D:\study\学习笔记\spring学习\6、依赖注入.assets\image-20220103183038917.png)]

5.技巧:

看spring等纯英文的官方文档时,英文看不懂时,可以先关注页面的代码【类似于当时看英文版的Thinking In Java的感觉】

6.判断两个对象是否相等,直接比较hashCode即可【直接相等比较,其实也是比较的hashCode】

7.本文章代码地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值