【MinaFile】【一】Spring读取xml的一种方式

来源:互联网 发布:焦作公务员网络培训 编辑:程序博客网 时间:2024/06/08 18:48

这是通过Spring来读取XML文件的分享。

首先。目录结构如图。是用Maven来进行Spring的Jar包管理。

一、写Maven配置文件

去官网,就能看到Spring提供的Maven配置文件。

<dependencies>    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-context</artifactId>        <version>4.2.4.RELEASE</version>    </dependency></dependencies>

把上面的依赖放入pom中就可以搭建Spring的简单环境了。博主写的这篇文章的时候,Spring的版本最高的4.2.4。反正这个依赖在官网上挺显眼的,就直接拿来用了。




二、写资源文件

2.1 资源文件由两个文件组成,一个filePath.properties和一个applicationContext.xml文件。


2.2 filePath.properties文件中的代码如下。

bjsyPath=123465sdhlPath=1234jcjtPath=1231bjsy=/bjsys/filessdhl=/sdhl/src/file


2.3 applicationContext.xml文件中的代码如下。

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd"><beans default-merge="true"><!-- 配置文件的路径 -->    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">        <property name="locations">            <list>                <value>classpath:filePath.properties</value>            </list>        </property>    </bean>    <!-- 类Bean。注意:这里的propertyName的名字要和类中的属性一致。不然会报错 --><bean id="propertiesModel" class="com.minafile.model.PropertiesModel">           <property name="bjsyPath" value="${bjsyPath}" />          <property name="sdhlPath" value="${sdhlPath}" />          <property name="jcjtPath" value="${jcjtPath}" />          <property name="bjsy" value="${bjsy}" />          <property name="sdhl" value="${sdhl}" />      </bean> </beans>

三、写类Model

这里的model的属性字段和配置文件中的bean的属性名一致。

package com.minafile.model;public class PropertiesModel {private String <span style="background-color: rgb(255, 255, 255);">bjsyPath</span>;private String sdhlPath;private String jcjtPath;private String bjsy;private String sdhl;public String getBjsyPath() {return bjsyPath;}public void setBjsyPath(String bjsyPath) {this.bjsyPath = bjsyPath;}public String getSdhlPath() {return sdhlPath;}public void setSdhlPath(String sdhlPath) {this.sdhlPath = sdhlPath;}public String getJcjtPath() {return jcjtPath;}public void setJcjtPath(String jcjtPath) {this.jcjtPath = jcjtPath;}public String getBjsy() {return bjsy;}public void setBjsy(String bjsy) {this.bjsy = bjsy;}public String getSdhl() {return sdhl;}public void setSdhl(String sdhl) {this.sdhl = sdhl;}}

四、可以读了

    

package com.minafile.util; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.minafile.model.PropertiesModel;public class ReadProperties {// xml文件名。private static ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(      "applicationContext.xml");public static void main(String[] args) {// 读取bean。PropertiesModel d = (PropertiesModel) context.getBean("propertiesModel");System.out.println(d.getBjsy());System.out.println(d.getBjsyPath());}}

五、看输出



最新代码在github上。欢迎fork。

项目名:MinaFile

0 0
原创粉丝点击