【第5章】spring命名空间和数据源的引入-一、命名空间

时间:2024-04-14 17:37:22

1. 引入

<?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:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
</beans>

2. util

util主要是关于对集合类参数简化,spring bean通过类似于引入外部bean的形式使用

<!--util:list、map、set-->
<util:list id="bookList">
    <value>2024-03-29</value>
    <value>2024-03-30</value>
    <value>2024-03-31</value>
</util:list>
<util:map id="bookMap">
    <entry>
        <key>
            <value>Sean Brdiy</value>
        </key>
        <value>This is good idea!</value>
    </entry>
    <entry>
        <key>
            <value>version</value>
        </key>
        <ref bean="version"></ref>
    </entry>
</util:map>
<util:set id="bookSet">
    <value>1</value>
    <value>2</value>
    <value>3</value>
    <value>4</value>
    <value>5</value>
</util:set>
<bean id="book8" class="org.example.di.Book">
    <property name="upgradeDate">
        <ref bean="bookList"></ref>
    </property>
    <property name="readerComments">
        <ref bean="bookMap"></ref>
    </property>
    <property name="pageSize">
        <ref bean="bookSet"></ref>
    </property>
</bean>
<util:properties id="mysql" location="classpath:jdbc.properties"></util:properties>

3. p

p命名空间主要是简化property标签,防止属性过多,让结构看上去复杂

<!--p命名空间-->
<bean id="book9" class="org.example.di.Book" p:bName="java编程思想" p:author="Bruce Eckel"
      p:master-ref="version" p:upgradeDate-ref="bookList" p:readerComments-ref="bookMap" p:pageSize-ref="bookSet">
</bean>

4. context

context主要用于扫描指定包路径下的spring bean和开启注解及加载配置文件

<context:component-scan base-package="org.example"></context:component-scan>
<context:annotation-config></context:annotation-config>
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>