程序中需要一些常量,但可能因为突变情况而得去改变这些常量,如果在程序中写死的话,难免会很不方便,没有灵活性。
这样就想起了以前写算法题时用程序读文件,改文件总比改程序好吧。。
Spring通过配置可以读取2种格式的配置文件,xml和properties文件。
1、读XML文件
首先你得有一个需要读取变量对应的javaBean
public class Test
{
private int var;
//setter和getter
//...
}
在spring中配置这个javaBean,id为test.
然后自制一个XML配置文件,里面放入需要读取的值,形式如下:
<xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="test" class="Test类的路径">
<property name="var">
<value>20</value>
</property>
</bean>
</beans>
使用有两种方法:
a.利用ClassPathXmlApplicationContext
ApplicationContext context = new ClassPathXmlApplicationContext("xxx.xml");
Test test = (Test)context.getBean("test");
System.out.println(test.getVar());
b.利用FileSystemResource读取
Resource rs = new FileSystemResource("xxx.xml文件的路径");
BeanFactory factory = new XmlBeanFactory(rs);
Test test = (Test)factory.getBean("test");\
System.out.println(test.getVar());
2、读Properties文件
还用上面的Test类
自制xxx.properties文件
test.class=package.Test //package为Test的包地址,test为Test对应的javaBean
test.var=10
利用org.springframework.beans.factory.support.PropertiesBeanDefinitionReader来读取属性文件
BeanDefinitionRegistry reg = new DefaultListableBeanFactory();
PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(reg);
reader.loadBeanDefinitions(new ClassPathResource("xxx.properties"));
BeanFactory factory = (BeanFactory)reg;
Test test = (Test)factory.getBean("test");
System.out.println(test.getVar());
当然也可以直接用JAVA文件操作来读取.
分享到:
相关推荐
spring读取配置不同目录下的配置文件,使用ClassPathXmlApplicationContext与FileSystemXmlApplicationContext
NULL 博文链接:https://konghaibo.iteye.com/blog/430146
主要介绍了Spring读取配置文件属性实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
本文档是很专业的 Spring动态加载配置文件,实现热部署方案。
NULL 博文链接:https://songwensheng.iteye.com/blog/629578
Spring Boot读取配置文件常用方式
我们使用Spring Boot编写多个模块开发时,我们希望各个模块使用各自的配置文件,避免将整个项目的配置文件都写在一起,从而降低各个模块之间的耦合度。
spring读取properties配置文件的key值。
NULL 博文链接:https://jiachenmianyu.iteye.com/blog/1745042
Spring Boot中配置文件介绍及其使用教程所用到的Controller代码 Spring Boot中配置文件介绍及其使用教程所用到的Controller代码 Spring Boot中配置文件介绍及其使用教程所用到的Controller代码 Spring Boot中配置...
主要给大家介绍了Spring Batch读取txt文件并写入数据库的方法,SpringBatch 是一个轻量级、全面的批处理框架。这里我们用它来实现文件的读取并将读取的结果作处理,处理之后再写入数据库中的功能。需要的朋友可以...
Spring源码分析:配置文件读取流程 - ImportNew
Spring之AOP配置文件详解.txt Spring之AOP配置文件详解.txt 帮助你更快张握Java的学习!
spring配置文件spring配置文件spring配置文件spring配置文件spring配置文件spring配置文件spring配置文件spring配置文件spring配置文件spring配置文件spring配置文件spring配置文件spring配置文件spring配置文件...
spring配置文件实例
Spring配置文件集合Spring配置文件集合Spring配置文件集合Spring配置文件集合Spring配置文件集合Spring配置文件集合Spring配置文件集合
初学Spring的小伙伴,还在为找不到主配置文件而着急吗,该配置文件是基于Spring4.10版本的,不用再自己到官网页面上到处找了,分享给大家,也希望大家别再像我一样因为这个坑耽误了大半天的时间,如果要自己配置也...
使用Spring配置文件实现AOP
struts2+spring+hibernate 配置文件struts2+spring+hibernate 配置文件