Spring(三)-IOC使用

2023-11-15

目录

基于XML管理bean

入门案例

引入依赖

创建类HelloWorld

创建Spring的配置文件

在Spring的配置文件中配置bean

创建测试类测试

思路

获取bean

方式一:根据id获取

方式二:根据类型获取

方式三:根据id和类型

总结

扩展

结论

依赖注入之setter注入

配置bean时为属性赋值

依赖注入之构造器注入

配置bean

特殊值处理

(1)字面量赋值

(2)null值 

(3)xml实体

(4)CDATA节

为类类型属性赋值

创建Clazz类

修改Student

方式一:引用外部已声明的bean

方式二:内部bean

方式三:级联属性赋值 

为数组类型属性赋值

修改Student

配置bean

测试

类类型的数组类型

为集合类型属性赋值

(1)为List集合类型属性赋值

(2)为Map集合类型属性赋值 

 (3)引用集合类型的bean

p命名空间 

引入外部属性文件

(1)加入依赖

(2)创建外部属性文件

(3)引入属性文件

(4)配置bean

(5)测试


基于XML管理bean

入门案例

引入依赖

pom.xml

        <!--Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--Spring end-->

创建类HelloWorld

com.spring.pojo.HelloWorld
public class HelloWorld {

    public void sayHello(){
        System.out.println("Spring Test");
    }
}

创建Spring的配置文件

创建applicationContext.xml

在Spring的配置文件中配置bean

<?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:配置一个bean对象,并将对象交给IOC容器管理
        id:bean的唯一标识,不能重复
        class:设置bean对象所对应的全类名
    -->
    <bean id="helloworld" class="com.spring.pojo.HelloWorld"></bean>
</beans>

创建测试类测试

com.kesteler.springTest.TestHelloWorld
public class TestHelloWorld {
    @Test
    public void test(){
        ApplicationContext ioc = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        HelloWorld helloWorld = (HelloWorld)ioc.getBean("helloworld");
        helloWorld.sayHello();
    }
}

思路

Spring配置

 com.spring.pojo下创建Student

package com.spring.pojo;

public class Student {
    private Integer sid;
    private String sname;
    private Integer age;
    private String gender;

    public Student(){

    }

    public Student(Integer sid, String sname, Integer age, String gender) {
        this.sid = sid;
        this.sname = sname;
        this.age = age;
        this.gender = gender;
    }

    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", sname='" + sname + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                '}';
    }
}

配置文件applicationContext.xml

<bean id="student1" class="com.spring.pojo.Student"></bean>

创建测试文件com.kesteler.springTest下的TestIOCXml.java

package com.kesteler.springTest;

import com.spring.pojo.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestIOCXml {
    @Test
    public void testIOC(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        Student student = (Student) ac.getBean("student1");
        System.out.println(student);
    }
}

 Spring 底层默认通过反射技术调用组件类的无参构造器来创建组件对象,这一点需要注意。如果在需要无参构造器时,没有无参构造器,则会抛出下面的异常:

获取bean

方式一:根据id获取

由于 id 属性指定了 bean 的唯一标识,所以根据 bean 标签的 id 属性可以精确获取到一个组件对象。

    @Test
    public void testIOC(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        Student student = (Student) ac.getBean("student1");
        System.out.println(student);
    }

方式二:根据类型获取

    @Test
    public void testIOC(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        //Student student = (Student) ac.getBean("student1");
        Student student = (Student)ac.getBean(Student.class);
        System.out.println(student);
    }

这里如果在配置文件中同一个类配置多个id会发生什么呢?

 说明在配置文件中一个类出现一次即可,要用类名获取对象的话,需要查看配置文件有无同一个类不同id的情况。

如果一个类都不配置呢

 当使用类名去获取对象,仅有且必须有配置一个id

方式三:根据id和类型

    @Test
    public void testIOC(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        //Student student = (Student) ac.getBean("student1");
        //Student student = (Student)ac.getBean(Student.class);
        Student student = (Student)ac.getBean("student1",Student.class);
        System.out.println(student);
    }

总结

当根据类型获取bean时,要求IOC容器中指定类型的bean有且只能有一个。

所以常用的是第2种方式,根据类型获取。

因为类名往往配置一个即可,如果像配置多个,可以用scope属性更改,可选择单例或者多例:

扩展

如果组件类实现了接口,根据接口类型可以获取 bean 吗?

可以,前提是bean唯一

创建一个Person接口,Student实现Person

public class Student implements Person

测试程序

    @Test
    public void testIOC(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        //Student student = (Student) ac.getBean("student1");
        //Student student = (Student)ac.getBean(Student.class);
        //Student student = (Student)ac.getBean("student1",Student.class);
        Student student = (Student)ac.getBean(Person.class);
        System.out.println(student);
    }

如果一个接口有多个实现类,这些实现类都配置了 bean,根据接口类型可以获取 bean 吗?

不行,因为bean不唯一

创建Worker实现Person

package com.spring.pojo;

public class Worker implements Person {
    private Integer wid;
    private String wname;
    private Integer age;
    private String gender;

    public Worker() {
    }

    public Worker(Integer wid, String wname, Integer age, String gender) {
        this.wid = wid;
        this.wname = wname;
        this.age = age;
        this.gender = gender;
    }

    public Integer getWid() {
        return wid;
    }

    public void setWid(Integer wid) {
        this.wid = wid;
    }

    public String getWname() {
        return wname;
    }

    public void setWname(String wname) {
        this.wname = wname;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}

继续上一个测试程序

    @Test
    public void testIOC(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        //Student student = (Student) ac.getBean("student1");
        //Student student = (Student)ac.getBean(Student.class);
        //Student student = (Student)ac.getBean("student1",Student.class);
        Student student = (Student)ac.getBean(Person.class);
        System.out.println(student);
    }

结论

根据类型来获取bean时,在满足bean唯一性的前提下,其实只是看:『对象 instanceof 指定的类型』的返回结果,只要返回的是true就可以认定为和类型匹配,能够获取到。

依赖注入之setter注入

set注入实际上是调用实体类中的set方法,所以数据库字段其实是和实体类中的set和get方法中的get和set后面的部分映射

配置bean时为属性赋值

    <bean id="student2" class="com.spring.pojo.Student">
        <property name="sid" value="1"></property>
        <property name="sname" value="张三"></property>
        <property name="age" value="3"></property>
        <property name="gender" value="男"></property>
    </bean>

测试

    @Test
    public void testIOC2(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        Student student = (Student) ac.getBean("student2",Student.class);
        System.out.println(student);
    }

依赖注入之构造器注入

实体类中必须有有参构造函数

配置bean

注意:
constructor-arg标签还有两个属性可以进一步描述构造器参数:
index属性:指定参数所在位置的索引(从0开始)
name属性:指定参数名

    <bean id="student3" class="com.spring.pojo.Student">
        <constructor-arg value="2"></constructor-arg>
        <constructor-arg value="李四"></constructor-arg>
        <constructor-arg value="4"></constructor-arg>
        <constructor-arg value="女"></constructor-arg>
    </bean>

 测试

    @Test
    public void testIOC3(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        Student student = (Student) ac.getBean("student3",Student.class);
        System.out.println(student);
    }

 在不加Index的情况下是按照构造函数的参数顺序来的,如果顺序有变,可以通过Index赋值

    <bean id="student3" class="com.spring.pojo.Student">
        <constructor-arg value="2"></constructor-arg>
        <constructor-arg value="4"></constructor-arg>
        <constructor-arg value="李四"></constructor-arg>
        <constructor-arg value="女"></constructor-arg>
    </bean>

 报错:Could not convert argument value of type [java.lang.String] to required type [java.lang.Integer]

原因即是第三个参数age是Integer,无法将String转换成Integer

 修改:

    <bean id="student3" class="com.spring.pojo.Student">
        <constructor-arg value="2"></constructor-arg>
        <constructor-arg value="4" index="2"></constructor-arg>
        <constructor-arg value="李四" index="1"></constructor-arg>
        <constructor-arg value="女"></constructor-arg>
    </bean>

 总结:

1.当construcrot-arg未按构造函数的参数顺序来时,可通过index或者name去指定。

2.当同时有两个有参构造函数时,无法自动适配到使用哪个构造函数,就必须通过name属性去适配构造函数。

特殊值处理

(1)字面量赋值

什么是字面量?
int a = 10;
声明一个变量a,初始化为10,此时a就不代表字母a了,而是作为一个变量的名字。当我们引用a的时候,我们实际上拿到的值是10。
而如果a是带引号的:‘a’,那么它现在不是一个变量,它就是代表a这个字母本身,这就是字面量。所以字面量没有引申含义,就是我们看到的这个数据本身。

(2)null值 

区分:

        <constructor-arg name="gender">
            <null></null>
        </constructor-arg>

 和

        <constructor-arg name="gender" value="null"></constructor-arg>

两者测试程序运行后得到的输出显示是一样的

 但实质区别,一个是空值null,一个字符串“null”

(3)xml实体

<!-- 小于号在XML文档中用来定义标签的开始,不能随便使用 -->
<!-- 解决方案一:使用XML实体来代替 -->
<property name="expression" value="a &lt; b"/>

<!-- 小于号&lt; 大于号&gt; -->

(4)CDATA节

用<![CDATA[expression]]>包裹着就不需要转义

<property name="expression">
<!-- 解决方案二:使用CDATA节 -->
<!-- CDATA中的C代表Character,是文本、字符的含义,CDATA就表示纯文本数据 -->
<!-- XML解析器看到CDATA节就知道这里是纯文本,就不会当作XML标签或属性来解析 -->
<!-- 所以CDATA节中写什么符号都随意 -->
<value><![CDATA[a < b]]></value>
</property>

这里注意CDATA节必须放在value标签中,不能在value属性内部出现。

    <bean id="student4" class="com.spring.pojo.Student">
        <constructor-arg value="3"></constructor-arg>
        <constructor-arg value="5" index="2"></constructor-arg>
        <constructor-arg index="1">
            <value><![CDATA[<王五>]]></value>
        </constructor-arg>
        <constructor-arg value="男"></constructor-arg>
    </bean>

测试

    @Test
    public void testIOC4(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        Student student = (Student) ac.getBean("student4",Student.class);
        System.out.println(student);
    }

这里有个小细节

    <bean id="student4" class="com.spring.pojo.Student">
        <constructor-arg value="3"></constructor-arg>
        <constructor-arg value="5" index="2"></constructor-arg>
        <constructor-arg index="1">
            <value>
                <![CDATA[
                    <王五>
                ]]>
            </value>
        </constructor-arg>
        <constructor-arg value="男"></constructor-arg>
    </bean>

 

为类类型属性赋值

创建Clazz类

com.spring.pojo下 

package com.spring.pojo;

public class Clazz {
    private Integer cid;
    private String cname;

    public Clazz() {
    }

    public Clazz(Integer cid, String cname) {
        this.cid = cid;
        this.cname = cname;
    }

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    @Override
    public String toString() {
        return "Clazz{" +
                "cid=" + cid +
                ", cname='" + cname + '\'' +
                '}';
    }
}

修改Student

package com.spring.pojo;

public class Student implements Person {
    private Integer sid;
    private String sname;
    private Integer age;
    private String gender;
    private Class clazz;

    public Student(){

    }

    public Student(Integer sid, String sname, Integer age, String gender) {
        this.sid = sid;
        this.sname = sname;
        this.age = age;
        this.gender = gender;
    }

    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Class getClazz(){return clazz;}

    public void setClazz(Class clazz){
        this.clazz = clazz;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", sname='" + sname + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ",clazz=" + clazz +
                '}';
    }
}

 Clazz是类,不能直接用字面量赋值,可以使用以下三种方法:

方式一:引用外部已声明的bean

ref作用:引用IOC容器中的某个bean的id

    <bean id="student5" class="com.spring.pojo.Student">
        <property name="sid" value="5"></property>
        <property name="sname" value="周五"></property>
        <property name="age" value="5"></property>
        <property name="gender" value="男"></property>
        <property name="clazz" ref="class1"></property>
    </bean>
    <bean id="class1" class="com.spring.pojo.Clazz">
        <property name="cid" value="1001"></property>
        <property name="cname" value="一班"></property>
    </bean>

测试

    @Test
    public void testIOC5(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        Student student = (Student) ac.getBean("student5",Student.class);
        System.out.println(student);
    }

方式二:内部bean

applicationContext.xml

    <bean id="student6" class="com.spring.pojo.Student">
        <property name="sid" value="6"></property>
        <property name="sname" value="吴六"></property>
        <property name="age" value="6"></property>
        <property name="gender" value="女"></property>
        <property name="clazz">
            <bean id="class2" class="com.spring.pojo.Clazz">
                <property name="cid" value="1001"></property>
                <property name="cname" value="一班"></property>
            </bean>
        </property>
    </bean>
TestIOCXml.java测试
    @Test
    public void testIOC6(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        Student student = (Student) ac.getBean("student6",Student.class);
        System.out.println(student);
    }

 内部Bean只能在当前Bean的内部使用,不能直接通过ioc来获取。

方式三:级联属性赋值 

applicationContext.xml,利用方式一中已声明的外部class1

    <bean id="student7" class="com.spring.pojo.Student">
        <property name="sid" value="6"></property>
        <property name="sname" value="吴六"></property>
        <property name="age" value="6"></property>
        <property name="gender" value="女"></property>
        <property name="clazz" ref="class1"></property>
        <property name="clazz.cid" value="1002"></property>
        <property name="clazz.cname" value="二班"></property>
    </bean>

TestIOCXml.java测试

    @Test
    public void testIOC7(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        Student student = (Student) ac.getBean("student7",Student.class);
        System.out.println(student);
    }

为数组类型属性赋值

修改Student

package com.spring.pojo;

import java.lang.reflect.Array;
import java.util.Arrays;

public class Student implements Person {
    private Integer sid;
    private String sname;
    private Integer age;
    private String gender;
    private Clazz clazz;
    private String[] hobby;
    private Clazz[] classArray;

    public Student(){

    }

    public Student(Integer sid, String sname, Integer age, String gender) {
        this.sid = sid;
        this.sname = sname;
        this.age = age;
        this.gender = gender;
    }

    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Clazz getClazz(){return clazz;}

    public void setClazz(Clazz clazz){
        this.clazz = clazz;
    }

    public String[] getHobby(){return hobby;}

    public void setHobby(String[] hobby){
        this.hobby = hobby;
    }

    public Clazz[] getClassArray(){return classArray;}

    public void setClassArray(Clazz[] classArray){
        this.classArray = classArray;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", sname='" + sname + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ",clazz=" + clazz +
                ",hobby=" + Arrays.toString(hobby) +
                ",classArray=" + Arrays.toString(classArray) +
                '}';
    }
}

配置bean

applicationContext.xml

    <bean id="student8" class="com.spring.pojo.Student">
        <property name="sid" value="8"></property>
        <property name="sname" value="王八"></property>
        <property name="age" value="8"></property>
        <property name="gender" value="男"></property>
        <property name="clazz" ref="class1"></property>
        <property name="clazz.cid" value="1002"></property>
        <property name="clazz.cname" value="二班"></property>
        <property name="hobby">
            <array>
                <value>篮球</value>
                <value>足球</value>
                <value>乒乓</value>
            </array>
        </property>
    </bean>

测试

TestIOCXml.java

    @Test
    public void testIOC8(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        Student student = (Student) ac.getBean("student8",Student.class);
        System.out.println(student);
    }

类类型的数组类型

    <bean id="student8" class="com.spring.pojo.Student">
        <property name="sid" value="8"></property>
        <property name="sname" value="王八"></property>
        <property name="age" value="8"></property>
        <property name="gender" value="男"></property>
        <property name="clazz" ref="class1"></property>
        <property name="clazz.cid" value="1002"></property>
        <property name="clazz.cname" value="二班"></property>
        <property name="hobby">
            <array>
                <value>篮球</value>
                <value>足球</value>
                <value>乒乓</value>
            </array>
        </property>
        <property name="classArray">
            <array>
                <ref bean="class3"></ref>
            </array>
        </property>
    </bean>
    <bean id="class3" class="com.spring.pojo.Clazz">
        <property name="cid" value="1003"></property>
        <property name="cname" value="三班"></property>
    </bean>

为集合类型属性赋值

(1)为List集合类型属性赋值

在Clazz类中添加以下代码:

package com.spring.pojo;

import java.util.List;

public class Clazz {
    private Integer cid;
    private String cname;
    private List<Student> students;

    public Clazz() {
    }

    public Clazz(Integer cid, String cname) {
        this.cid = cid;
        this.cname = cname;
    }

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    @Override
    public String toString() {
        return "Clazz{" +
                "cid=" + cid +
                ", cname='" + cname + '\'' +
                ", students=" + students +
                '}';
    }
}

方式一:内部的list结合

配置applicationContext.xml:

这里注意list标签内部的属性也有value和ref,其中value用来赋值字面量,ref用来赋值类类型的引用。

    <bean id="class4" class="com.spring.pojo.Clazz">
        <property name="cid" value="1004"></property>
        <property name="cname" value="四班"></property>
        <property name="students">
            <list>
                <ref bean="student2"></ref>
                <ref bean="student3"></ref>
                <ref bean="student4"></ref>
            </list>
        </property>
    </bean>

 方式二:引用list集合的bean

在applicationContext.xml中增加bean

    <!-- 方式二:引用list集合的bean -->
    <!--
        配置一个集合类型的bean需要用到新的约束util
     -->
    <bean id="class5" class="com.spring.pojo.Clazz">
        <property name="cid" value="1005"></property>
        <property name="cname" value="五班"></property>
        <property name="students" ref="studentList"></property>
    </bean>
    <!-- 集合类型的Bean -->
    <util:list id="studentList">
        <ref bean="student2"></ref>
        <ref bean="student3"></ref>
        <ref bean="student4"></ref>
    </util:list>

 这里会出现报错:

namespace "util" is not bound

 这需要applicationContext.xml中添加

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

随后会报错

但无法找到元素 'util:list' 的声明

applicationContext.xml中添加 

xmlns:p="http://www.springframework.org/schema/p"
http://www.springframework.org/schema/util  http://www.springframework.org/schema/util/spring-util-4.3.xsd

 解决报错后,TestIOCXml.java测试程序:

    @Test
    public void testIOC_Class5(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        Clazz clazz = (Clazz) ac.getBean("class5",Clazz.class);
        System.out.println(clazz);
    }

 若为Set集合类型属性赋值,只需要将其中的list标签改为set标签即可

(2)为Map集合类型属性赋值 

创建教师类Teacher:

package com.spring.pojo;

public class Teacher {
    private Integer tid;
    private String tname;

    public Teacher() {
    }

    public Teacher(Integer tid, String tname) {
        this.tid = tid;
        this.tname = tname;
    }

    public Integer getTid() {
        return tid;
    }

    public void setTid(Integer tid) {
        this.tid = tid;
    }

    public String getTname() {
        return tname;
    }

    public void setTname(String tname) {
        this.tname = tname;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "tid=" + tid +
                ", tname='" + tname + '\'' +
                '}';
    }
}

 修改Student.java,添加Map属性

package com.spring.pojo;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Map;

public class Student implements Person {
    private Integer sid;
    private String sname;
    private Integer age;
    private String gender;
    private Clazz clazz;
    private String[] hobby;
    private Clazz[] classArray;
    private Map<String,Teacher> teacherMap;

    public Student(){

    }

    public Student(Integer sid, String sname, Integer age, String gender) {
        this.sid = sid;
        this.sname = sname;
        this.age = age;
        this.gender = gender;
    }

    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Clazz getClazz(){return clazz;}

    public void setClazz(Clazz clazz){
        this.clazz = clazz;
    }

    public String[] getHobby(){return hobby;}

    public void setHobby(String[] hobby){
        this.hobby = hobby;
    }

    public Clazz[] getClassArray(){return classArray;}

    public void setClassArray(Clazz[] classArray){
        this.classArray = classArray;
    }

    public Map<String,Teacher> getTeacherMap(){
        return teacherMap;
    }

    public void setTeacherMap(Map<String,Teacher> teacherMap){
        this.teacherMap = teacherMap;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", sname='" + sname + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ",clazz=" + clazz +
                ",hobby=" + Arrays.toString(hobby) +
                ",classArray=" + Arrays.toString(classArray) +
                ", teacherMap=" + teacherMap +
                '}';
    }
}

map集合赋值方法一:通过map标签

applicationContext.xml中配置bean:

    <bean id="student9" class="com.spring.pojo.Student">
        <property name="sid" value="9"></property>
        <property name="sname" value="冯九"></property>
        <property name="age" value="9"></property>
        <property name="gender" value="男"></property>
        <property name="clazz" ref="class1"></property>
        <property name="clazz.cid" value="1002"></property>
        <property name="clazz.cname" value="二班"></property>
        <property name="hobby">
            <array>
                <value>篮球</value>
                <value>足球</value>
                <value>乒乓</value>
            </array>
        </property>
        <property name="teacherMap">
            <map>
                <!--
                                    一个entry表示一个键值对
                                    key-ref 引用类型的键
                                    key 字面量类型的键
                                    value-ref 引用类型的值
                                    value 字面量类型的值
                                 -->
                <entry key="1001" value-ref="teacher1"></entry>
                <entry key="1002" value-ref="teacher2"></entry>
            </map>
        </property>
    </bean>
    <bean id="teacher1" class="com.spring.pojo.Teacher">
        <property name="tid" value="1001"></property>
        <property name="tname" value="赵老师"></property>
    </bean>
    <bean id="teacher2" class="com.spring.pojo.Teacher">
        <property name="tid" value="1002"></property>
        <property name="tname" value="钱老师"></property>
    </bean>

 TestIOCXml.java测试

    @Test
    public void testIOC9(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        Student student = (Student) ac.getBean("student9",Student.class);
        System.out.println(student);
    }

 map集合赋值方法二:通过< util:map >标签

在applicationContext.xml中新配置Bean

    <util:map id="teacherMap1">
        <entry key="1001" value-ref="teacher1"></entry>
        <entry key="1002" value-ref="teacher2"></entry>
    </util:map>
    <bean id="student10" class="com.spring.pojo.Student">
        <property name="sid" value="10"></property>
        <property name="sname" value="陈十"></property>
        <property name="age" value="10"></property>
        <property name="gender" value="女"></property>
        <property name="clazz" ref="class1"></property>
        <property name="clazz.cid" value="1002"></property>
        <property name="clazz.cname" value="二班"></property>
        <property name="hobby">
            <array>
                <value>篮球</value>
                <value>足球</value>
                <value>乒乓</value>
            </array>
        </property>
        <property name="teacherMap" ref="teacherMap1"></property>
    </bean>

 TestIOCXml.java测试

    @Test
    public void testIOC10(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        Student student = (Student) ac.getBean("student10",Student.class);
        System.out.println(student);
    }

 (3)引用集合类型的bean

使用util:list、util:map标签必须引入相应的命名空间,可以通过idea的提示功能选择 

p命名空间 

在applicationContext.xml中添加Bean

    <bean id="student11" class="com.spring.pojo.Student" p:sid="11" p:sname="褚十一" p:age="36" p:gender="女"
          p:teacherMap-ref="teacherMap1"></bean>

 注意这里要引入p标签的命名空间

 TestIOCXml.java测试程序:

    @Test
    public void testIOC11(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
        Student student = (Student) ac.getBean("student11",Student.class);
        System.out.println(student);
    }

引入外部属性文件

加入德鲁伊数据库连接池的依赖 

(1)加入依赖

在pom.xml中加入依赖

        <!-- 德鲁伊数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.9</version>
        </dependency>

创建核心配置文件spring-datasource.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 http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/mybtistest"></property>
        <property name="username" value="root"></property>
        <property name="password" value="000000"></property>
        <!-- 初始化的连接 -->
        <property name="initialSize" value="10"></property>
        <!-- 最大连接数 -->
        <property name="maxActive" value="200"></property>
    </bean>

</beans>

创建TestDataSource.java

package com.kesteler.springTest;

import com.alibaba.druid.pool.DruidDataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.sql.SQLException;

public class TestDataSource {
    @Test
    public void dataSourceTest(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("config/spring-datasource.xml");
        DruidDataSource druidDataSource = (DruidDataSource) ac.getBean("datasource",DruidDataSource.class);
        try {
            System.out.println(druidDataSource.getConnection());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        druidDataSource.close();
    }
}

(2)创建外部属性文件

创建jdbc.properties,配置数据库

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybtistest
jdbc.username=root
jdbc.password=000000

(3)引入属性文件

spring-datasource.xml中引入属性文件

    <!-- 引入jdbc.properties,之后可以通过${key}的方式来访问value -->
    <context:property-placeholder location="/jdbc.properties"></context:property-placeholder>

(4)配置bean

spring-datasource.xml中配置bean

    <bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property><!--"com.mysql.cj.jdbc.Driver"-->
        <property name="url" value="${jdbc.url}"></property><!--"jdbc:mysql://localhost:3306/mybtistest"-->
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <!-- 初始化的连接 -->
        <property name="initialSize" value="10"></property>
        <!-- 最大连接数 -->
        <property name="maxActive" value="200"></property>
    </bean>

(5)测试

使用上面的测试程序

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring(三)-IOC使用 的相关文章

  • Spring安全+LocaleResolver

    我需要在身份验证成功后更改区域设置 区域设置解析器
  • 卡夫卡监听器中的钩子

    kafka 监听消息之前 之后是否有任何类型的钩子可用 使用案例 必须设置MDC关联id才能进行日志溯源 我在寻找什么 之前 之后回调方法 以便可以在进入时设置 MDC 关联 ID 并最终在退出时清除 MDC 编辑后的场景 我将关联 id
  • 模式更新后 jOOQ 生成的类的运行时验证?

    我用org jooq util DefaultGenerator在构建过程中生成 jOOQ 类来表示我的数据库模式 当应用程序运行时 架构预计会在应用程序不知情的情况下发生更改 此类更改可能与已生成的代码兼容 也可能不兼容 如何在运行时检测
  • 始终等待页面加载到 PageObjects 上

    因此 当出现问题时 我只是创建了一个简单的 selenium JBehave 代码 我将首先发布简化的代码 然后稍后解释我的问题是什么 所以这里我们有一个简单的 AbstractClass 它将在我的 PageObjects 上继承 此类仅
  • 有没有办法让Maven自动下载快照版本?

    所以我有一个项目依赖于另一个项目的快照版本 依赖关系是
  • org.openqa.selenium.NoSuchSessionException:会话 ID 为空。调用 quit() 后使用 WebDriver?

    我已经进行了一些搜索 但仍然遇到同样的问题 我相信这可能是由于我的网络驱动程序是静态的造成的 我不太确定 在我的主课中 我包括了 BeforeTest and AfterTest BeforeTest包括根据我的 XML 文件启动新浏览器
  • Eclipse 无法识别 persistence.xml 的内容

    我在 eclipse 中收到以下错误 persistence xml 文件没有可识别的内容 我的 persistence xml 文件在我的应用程序中工作得很好 但 eclipse 一直给我这个错误 我在移动文件并使用 m2eclipse
  • Eclipse Oxygen - 该项目未构建,因为其构建路径不完整

    我刚刚安装了 Eclipse Oxygen 并尝试在工作台中打开现有项目 但收到此错误 该项目未构建 因为其构建路径不完整 不能 找到 java lang Object 的类文件 修复构建路径然后尝试 建设这个项目 我尝试右键单击该项目 转
  • SSLContext 初始化

    我正在看JSSE参考指南 我需要获取一个实例SSLContext为了创建一个SSLEngine 所以我可以使用它Netty以启用安全性 获取实例SSLContext I use SSLContext getInstance 我看到该方法被重
  • Eclipse RCP - 将视图与编辑器区域堆叠?

    在开发 Eclipse RCP 应用程序时 是否可以将视图与编辑器区域堆叠在一起 像这样 我有多个列表 表格 我想创建一种预览组合 当通过单击鼠标选择列表上的项目时 我希望我的预览合成显示该项目的数据 如果用户双击某个项目 我想在预览合成后
  • 我可以使用 Selenium Webdriver 测试元素的顺序吗?

    有一个表单 其中有 3 个字段 具有 3 个不同的 ID fieldset div div fieldset
  • Jersey 和 Spring 中的全局异常处理?

    我正在使用 Jersey 和 Spring 3 2 以及 Open CMIS 开发 RESTful Web 服务 我没有使用 Spring 的 MVC 模式 它只是 Spring IOC 和 Jersey SpringServlet 控制器
  • SQlite 获取最近的位置(带有纬度和经度)

    我的 SQLite 数据库中存储有纬度和经度的数据 我想获取距我输入的参数最近的位置 例如我当前的位置 纬度 经度等 我知道这在 MySQL 中是可能的 并且我已经做了相当多的研究 SQLite 需要一个自定义外部函数来实现半正弦公式 计算
  • Web 服务客户端的 AXIS 与 JAX-WS

    我决定用Java 实现Web 服务客户端 我已经在 Eclipse 中生成了 Axis 客户端 并使用 wsimport 生成了 JAS WS 客户端 两种解决方案都有效 现在我必须选择一种来继续 在选择其中之一之前我应该 考虑什么 JAX
  • 在Java内存管理中,“PS”代表什么?

    每当我看到 Java 中对内存的引用时 各种空格总是以 PS 为前缀 PS 是什么意思 它开始困扰我 到目前为止我唯一的猜测是 泳池空间 但这将是多余的 例子 PS伊甸园空间 PS 幸存者空间 PS 终身空间 老一代 PS Perm Gen
  • Android - 从渲染线程内结束活动

    下午好 我不熟悉 android 中的活动生命周期 并且一直在尽可能地阅读 但我不知道如何以良好的方式解决以下问题 我有一个使用 GLSurfaceView 的活动来在屏幕上绘制各种内容 在这个 GLSurfaceView 的渲染线程中 我
  • 没有运算符与给定名称和参数类型匹配。您可能需要添加显式类型转换。 -- Netbeans、Postgresql 8.4 和 Glassfish

    我正在尝试使用 EclipseLink 在 Glassfish 中使用 JPA 编辑 Postgresql 中的表 当我插入一个实体时 它运行良好 但是 当我尝试编辑或删除同一实体时 它失败并出现以下错误 任何想法 Caused by Ex
  • 背景图像隐藏其他组件,例如按钮标签等,反之亦然

    如何解决此代码中组件的隐藏问题 代码运行没有错误 但背景图片不显示 如何更改代码以获取背景图像 使用验证方法时 它在validation 中创建错误 public class TEST public TEST String strm Jan
  • Volley 在第一次调用方法时返回 null

    我正在尝试使用 volley 从服务器检索数据 但是当我第一次调用此方法时 我收到服务器的响应 但该方法返回 null 如果我第二次调用它 我会得到最后的响应 public String retrieveDataFromServer Str
  • Java有没有类似微软CHESS的工具?

    是否有类似于 Microsoft 的现有 Java 工具CHESS http research microsoft com chess 或者 CHESS 源代码是否开放 以便我可以尝试将其转换为 Java 谷歌的织线工 http code

随机推荐

  • 专题详解-5G接入控制(1)

    相关文章会在公众号同步更新 公众号 5G通信大家学 持续更新的相关5G内容都是直接根据3GPP整理 保证更新内容的准确性 避免通过二手 甚至多手的资料 以讹传讹误导网友 最近工作中遇到了一些5G专网接入限制的问题 以前没仔细研究 借着解决这
  • angular路由参数路由跳转

    路由参数及跳转 本节介绍路由参数及跳转相关 准备工作 首先 我们需要将上一节的 CommentService UserService抽离成单独的文件 以便多处使用 ng g s components router study comment
  • Python入门_使用while循环计算1-100之间偶数和

    案例 计算1 100之间所有偶数的和 i 1 定义一个变量sum为0 用来存放和 sum 0 while i lt 100 每次sum和i相加 if i 2 0 sum i i 1 执行完之后 打印sum的值 print 1 100之间偶数
  • Nginx实现反向代理和负载均衡

    Nginx安装 本文章主要介绍下 如何使用Nginx来实现反向代理和负载均衡 Nginx安装和基础知识 可参考我的这篇文章 Nginx安装 Nginx实现反向代理 实现反向代理需要准备两台Nginx服务器 一台Nginx服务器A ip为 1
  • leetcode33. 搜索旋转排序数组

    整数数组 nums 按升序排列 数组中的值 互不相同 在传递给函数之前 nums 在预先未知的某个下标 k 0 lt k lt nums length 上进行了 旋转 使数组变为 nums k nums k 1 nums n 1 nums
  • 【Python编程】如何在 Jupyter Notebook 中切换虚拟环境

    如何在 Jupyter Notebook 中切换虚拟环境 一 操作步骤 1 首先切换到想要在 Jupyter Notebook 里使用的虚拟环境 conda activate 环境名称 2 安装 ipykernel conda instal
  • TCP详解(一)服务和首部介绍

    文章目录 引言 TCP的服务 TCP首部 引言 TCP全称传输控制协议 Transmission Control Protocol 它是一种传输层通信协议 提供了面向连接的 可靠的字节流服务 本文将会简要介绍TCP为应用层提供的服务以及TC
  • node基础之三:http 模块

    1 导入模块 const http require http 2 创建服务 const server http createServer request response gt 获取请求方法 request method 获取请求 url
  • 阿里云1核1G内存1M宽带可以支持多少IP访问量?

    阿里云1核CPU 1G内存 1M公网宽带云服务器够用吗 1M宽带可以支持多少IP的访问量 来说说1M宽带可以跑多少流量及1核1G服务器配置性能 1核 1G 1M宽带配置能跑多少IP 一般来讲 如果图片不多 每天3000PV是没问题的 如果将
  • 优秀的CobaltStrike插件推荐:编程

    优秀的CobaltStrike插件推荐 编程 CobaltStrike是一款功能强大的渗透测试工具 广泛应用于红队行动和网络安全评估 它的灵活性和可扩展性使得开发者可以编写自己的插件来增强其功能 在这篇文章中 我将向你推荐一些好用的Coba
  • java并发包:重入锁与Condition条件

    本文转载至 http blog csdn net a910626 article details 51900941 重入锁 这里介绍一下synchronized wait notify方法的替代品 或者说是增强版 重入锁 重入锁是可以完全替
  • redis--13--Jedis使用

    redis 13 Jedis使用 代码位置 https gitee com DanShenGuiZu learnDemo tree master redis learn jedis 1 redis conf 修改 允许远程连接 bind 1
  • Java异常-Exception

    一 异常介绍 基本概念 Java语言中 将程序执行中发生的不正常情况称为 异常 注 开发过程中的语法错误和逻辑错误不是异常 执行过程中所发生的异常事件可分为两大类 Error 错误 Java虚拟机无法解决的严重问题 如 JVM系统内部错误
  • 2023-05-18 题目

    2023 05 18 题目 1 String 字符串 String 不是基本数据类型 且是不能被继承的 因为string类被final修饰 源码 public final class String implements java io Se
  • [FreeRTOS入门学习笔记]定时器

    定时器的使用步骤 1 定义一个handle xTimerCreate创建 2 启动定时器 在Task1中调用 通过队列通知守护任务来执行定时器任务 要再config头文件中定义守护任务相关配置 虽然定时器是在task1中启动 但是定时器的任
  • qt实现opengl播放yuv视频

    qt使用opengl播放yuv视频 文章目录 qt使用opengl播放yuv视频 toc 1 实现效果 2 pro文件 3 xvideowidget h 4 xvideowidget cpp 更多精彩内容 个人内容分类汇总 1 实现效果 2
  • VS2022编译GDAL库报错: fatal error U1050: PROJ_INCLUDE should be defined. PROJ >= 6 is a required depende

    目录 场景复现 定位问题 解决方案 踩过的坑 场景复现 使用VS2022的Native Tools command prompt for 2022工具编译GDAL库时 报 fatal error U1050 PROJ INCLUDE sho
  • RTSP视频边缘计算网关EasyNVR在5G时代有什么运用价值?

    5G和互联网的发展在近几年一直被按下了加速键 物联网正在成为主流 毋庸置疑 云计算为越来越多智能设备的连接提供了基础 给我们生活带来了极大便利 而边缘计算是云计算物联当中的一个关键应用 当我们在考虑云计算带来的数据过度集中 信息传输堵塞问题
  • 2018年最好用的5个python网站开发框架

    python作为解释型脚本语言 是一种通用的编程语言 由于python社区拥有大量的库文件 框架和其他的一些实用工具 我们可以用python完成各种各样的任务 另外 由于python的代码构成和结构就像英语句子一样自然 这种语言的学习曲线也
  • Spring(三)-IOC使用

    目录 基于XML管理bean 入门案例 引入依赖 创建类HelloWorld 创建Spring的配置文件 在Spring的配置文件中配置bean 创建测试类测试 思路 获取bean 方式一 根据id获取 方式二 根据类型获取 方式三 根据i