0
点赞
收藏
分享

微信扫一扫

06 Spring集合注入&读取properties文件



文章目录

  • 1 Spring注入集合
  • 1.1 在目标类中添加接收集合的的变量并提供setter方法
  • 1.2 在配置文件中进行配置
  • 2 读取properties文件
  • 2.1 新开一个命名空间
  • 2.2 在resources目录下新建.properties配置文件
  • 2.3 在spring配置文件applicationContext.xml中引用配置文件信息
  • 2.4 配置文件需要关注的问题
  • 结尾彩蛋


1 Spring注入集合

1.1 在目标类中添加接收集合的的变量并提供setter方法

private ArrayList list;
    private Set set;
    private Map map;

    public void setSet(Set set) {
        this.set = set;
    }
    public void setList(ArrayList list) {
        this.list = list;
    }
    public void setMap(Map map) {
        this.map = map;
    }

1.2 在配置文件中进行配置

<bean id="studentDao" class="com.zinksl.dao.impl.StudentDao">
    <property name="list">
        <array>
            <value>alsdig</value>
            <value>alsdig2</value>
            <value>alsdig3</value>
        </array>
    </property>
    <property name="map">
       <map>
           <entry value="haha" key="1"/>
           <entry value="haha" key="1"/>
           <entry value="haha" key="1"/>
           <entry value="haha" key="1"/>
       </map>
    </property>
    <property name="set">
        <set>
            <value>shdfihsff</value>
            <value>shdfihsff1</value>
            <value>shdfihsff2</value>
            <value>shdfihsff3</value>
        </set>
    </property>
</bean>

2 读取properties文件

2.1 新开一个命名空间

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      	
       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/context
       http://www.springframework.org/schema/context/spring-context.xsd
">

06 Spring集合注入&读取properties文件_配置文件

2.2 在resources目录下新建.properties配置文件

06 Spring集合注入&读取properties文件_spring_02

2.3 在spring配置文件applicationContext.xml中引用配置文件信息

(1)使用context标签:加载properties文件
自己定义的属性名与系统环境变量名冲突:
在context标签中,添加system-properties-mode="NEVER"属性表示不加载系统环 境变量属性;
(2)往bean中注入内容

<context:property-placeholder location="jdbc.properties" />
<bean id="testbean" class="com.zinksl.dao.PropertiesTest">
        <property name="name" value="${jdbc.username}"/>
</bean>

2.4 配置文件需要关注的问题

  • 需要加载多个配置文件数据时:

方式1: 使用逗号隔开,加载多个文件
 <context:property-placeholder location=“jdbc.properties,jdbc2.properties” system-properties-mode=“NEVER”/>
方式2: 使用匹配符“”,加载所有.properties文件
 <context:property-placeholder location=".properties" system-properties-mode=“NEVER”/>
方式3: 使用,类路径+“”,加载当前项目所有.properties文件【标准格式,必须使用】
 <context:property-placeholder location="classpath:.properties" system-properties-mode=“NEVER”/>
方式4: 使用,类路径+“”,加载当前项目和jar包所有.properties文件【标准格式,必须使用】
 <context:property-placeholder location="classpath😗.properties" system-properties-mode=“NEVER”/>

举报

相关推荐

0 条评论