Java读取配置文件的五种方式
目录
一、ServletContext获取真实路径
二、通过ResourceBundle类获取配置文件资源
三、ClassLoader方式读取
四、使用Sping提供的PropertiesLoaderUtils类
五、@Value("${content}")方式
一、ServletContext获取真实路径
使用request的ServletContext获取文件的绝对路径,通过文件流读出来
优点:1、可以读取任意位置的文件
2、采用文件流读取,所以可以读取不同格式的文件
缺点:不能在servlet外面读取配置文件,必须要有HttpServletRequest,Web环境适用
public class ServletContextDemo {public void readByServletContext(HttpServletRequest request, HttpServletResponse response) throws IOException {// 获取文件的绝对地址String realPath = request.getServletContext().getRealPath("config.properties");// 使用InputStreamReader,指定编码格式,解决中文乱码InputStreamReader reader = new InputStreamReader(new FileInputStream(realPath),"GBK");Properties pros = new Properties();// 加载流文件pros.load(reader);// 通过key获取对应的值String userName = pros.getProperty("userName");String chineseName = pros.getProperty("chineseName");System.out.println(userName+":"+chineseName);System.out.println("真实地址:"+realPath);}
}
编写单元测试(使用SpringBoot的方式):
@RunWith(SpringRunner.class)
@SpringBootTest(classes=ServletContextDemo.class)
public class ServletContextDemoTest {private MockHttpServletRequest request;private MockHttpServletResponse response;@Beforepublic void setUp(){request = new MockHttpServletRequest();// 这里设不设置无所谓,主要是使用InputStreamReader时要致指定编码格式request.setCharacterEncoding("GBK");response = new MockHttpServletResponse();}@Testpublic void readByServletContext() throws IOException {ServletContextDemo demo = new ServletContextDemo();demo.readByServletContext(request,response);}
}
测试结果:
二、通过ResourceBundle类获取配置文件资源
优点:1、可以以全限定类名的方式加载资源
2、可以在非web应用里加载资源
缺点:只能加载类下面的资源文件,且只能读取properties文件
使用方式:
1.配置文件放在resource源包下,不用加后缀
PropertiesUtil.getProfileByResourceBundle("config");
2.放在包里面的
PropertiesUtil.getProfileByResourceBundle("com.test.config");
演示代码——获取指定key
public class Demo {public static void main(String[] args) throws IOException {// 使用文件名读取,不能带文件后缀ResourceBundle bundle = ResourceBundle.getBundle("config".trim());String userName = bundle.getString("userName");String chineseName = bundle.getString("chineseName");// 乱码// 解决文件读取乱码String newName = new String(chineseName.getBytes("ISO-8859-1"), "GBK");System.out.println(userName+" 转码前:"+chineseName+" 转码后:"+newName);}
}
测试结果:
演示代码——获取所有key
public class Demo {public static void main(String[] args) throws IOException {// 使用文件名读取,不能带文件后缀ResourceBundle bundle = ResourceBundle.getBundle("config".trim());// 拿到所有的keyEnumeration<String> keys = bundle.getKeys();while(keys.hasMoreElements()){// 遍历元素获取值String key = keys.nextElement();String value = bundle.getString(key);System.out.println(key+":"+value);}}
}
三、ClassLoader方式读取
优点:1、可以在非Web应用中读取配置资源信息,
2、可以读取任意的资源文件信息
缺点:只能加载类classes下面的资源文件
代码示例:
public class Demo {public static void main(String[] args) throws IOException {// 类加载器方式,使用相对路径InputStream stream = Demo.class.getClassLoader().getResourceAsStream("config.properties");// 解决中文乱码,使用了reader指定编码格式InputStreamReader reader = new InputStreamReader(stream,"GBK");Properties pros = new Properties();pros.load(reader);// 获取资源String userName = pros.getProperty("userName");String chineseName = pros.getProperty("chineseName");}
}
四、使用Sping提供的PropertiesLoaderUtils类
非常简单的一种方式,引入Spring的相关依赖即可
public class Demo {public static void main(String[] args) throws IOException {// 使用全限定名Properties props = PropertiesLoaderUtils.loadAllProperties("config.properties");// 获取资源String userName = props.getProperty("userName");}
}
五、@Value("${content}")方式
这里使用SpringBoot的方式:
1、首先引入SpringBoot的单元测试依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency>
2、需要读取的配置文件demo.properties
content=this_is_a_String
chineseContent=中文字符串
3、使用注解获取配置文件的内容,创建ValueDemo.java
@PropertySource("classpath:demo.properties")
//@Component
@Configuration
public class ValueDemo {@Value("${content}")// 使用注解获取值private String content;@Value("${chineseContent}")private String chineseContent;public String getContent() {return content;}public void setContent(String content) {this.content = content;}public String getChineseContent() {return chineseContent;}public void setChineseContent(String chineseContent) {this.chineseContent = chineseContent;}
}
@PropertySource可以指定读取的配置文件,通过@Value注解获取值;通常标识在@Configuration配置类上。
@Value注解可以用在字段和方法上,通常用于从属性配置文件中读取属性值,也可以设置默认值。
@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
SpringBoot默认使用一个全局的配置文件,配置文件名是固定的;
1.application.properties
2.application.yml(或者是yaml)
注:当读取的配置文件名不是以上命名时,需要使用@PropertySource注解指定读取的配置文件。
// 读取多个配置文件
@PropertySource(value = { "classpath:demo01.properties", "classpath:demo02.properties"})
public class UserSpringConfig {...
}
@Configuration和@Component的区别:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {@AliasFor(annotation = Component.class)String value() default "";
}
从定义来看, @Configuration
注解本质上还是 @Component
,因此 <context:component-scan/>
或者 @ComponentScan
都能处理@Configuration
注解的类。
4、创建SpringBoot启动类MyApplication.java
@SpringBootApplication
@ComponentScan(basePackages = "springdemo")//自动扫描组件,指定包
public class MyApplication {public static void main(String[] args) {Logger logger = LoggerFactory.getLogger(MyApplication.class);try {SpringApplication.run(MyApplication.class);logger.info("springBoot启动成功...");} catch (Exception e) {logger.info("SpringBoot启动失败...");}}
}
创建一个配置类,在配置类上添加 @ComponentScan 注解。该注解默认会扫描该类所在的包下所有的配置类,相当于之前的 <context:component-scan>
当扫描的文件不在启动类(MyApplication.java)所在的包时,需要在启动类上添加此注解,指明扫描的包。
5、启动单元测试获取结果
@RunWith(SpringRunner.class)
@SpringBootTest(classes= MyApplication.class)// classes属性将某些类纳入测试环境的容器中
public class ValueDemoTest {@Autowiredprivate ValueDemo valueDemo;@Testpublic void getContext() throws IOException, InterruptedException {// 不能直接new(空指针异常),需要使用注解注入@Autowired// ValueDemo valueDemo = new ValueDemo();String str = new String(valueDemo.getChineseContent().getBytes("ISO-8859-1"), "GBK");System.out.println("获取内容:"+valueDemo.getContent()+" 获取中文内容:"+str);}
}
在@SpringBootTest注解的参数classes中加入参数,表示将某些类纳入测试环境的容器中。上述案例中,使用@SpringBootTest(classes= ValueDemo.class)也可以得到预期结果
测试结果:
Java读取配置文件的五种方式相关推荐
- java加载配置文件_Java 读取配置文件的五种方式
方式一:采用ServletContext读取,读取配置文件的realpath,然后通过文件流读取出来. 因为是用ServletContext读取文件路径,所以配置文件可以放入在WEB-INF的clas ...
- springboot读取配置文件的三种方式
项目中springboot读取配置文件的三种方式: 1.使用Environment 2.使用@Value 3.使用@ConfigurationProperties注解映射到bean中,定义一个User ...
- Java读取证书的两种方式
关于证书基础以及创建.查看.删除.导入.导出以及其他功能详解请参照:Java使用keytool创建CA证书 Java读取证书有两种方式 1.从文件中读取 public static void main ...
- java clone方法_干货满满:Java中创建对象的五种方式详解
通常来说,对象具有状态和行为,变量用来表明对象的状态,方法表明对象所具有的行为. 作为Java开发者,我们通常都是使用依赖管理系统,比如Spring去创建Java对象,但使用管理系统创建对象并不是唯一 ...
- 【Java获取配置文件的2种方式】
获取Java配置文件信息的2种方法 第一种方式 第二种方式 切记第二种方式路径文件不带后缀!!! 区别 第一种方式 Properties properties = new Properties();I ...
- Java遍历Map的五种方式
一.遍历Map的五种方式 java中遍历map一般有五种方法,从最早的Iterator,到java5支持的foreach,再到java8的Lambda表达式. 如果只是获取key,或者value,推荐 ...
- JAVA解析xml的五种方式比较
1)DOM解析 DOM是html和xml的应用程序接口(API),以层次结构(类似于树型)来组织节点和信息片段,映射XML文档的结构,允许获取和操作文档的任意部分,是W3C的官方标准[优点]①允许应用 ...
- java读取配置文件的几种方法
在现实工作中,我们常常需要保存一些系统配置信息,大家一般都会选择配置文件来完成,本文根据笔者工作中用到的读取配置文件的方法小小总结一下,主要叙述的是spring读取配置文件的方法. 一.读取xml配置 ...
- Python 读取配置文件常用几种方式
我们在设计自动化测试框架的时候,经常使用到配置文件,而配置文件种类有很多,常见的配置文件格式有很多中:ini.yaml.xml.properties.txt.py等. 配置文件ini 虽然配置文件放置 ...
最新文章
- 一种广泛存在于Facebook、谷歌、小米、阿里等公司的研发组织管理方式
- @EnableAsync @Async 的详解
- MS Vs.net 2003 Sp1发布!
- org.hibernate.transientobjectexception:The given object has a null identifier: com.gxuwz.check.entit
- cryptogen (2)generate 生成证书再举例
- codeforces741C Arpa’s overnight party and Mehrdad’s silent entering(二分图)
- angular组件--tips提示功能
- 如何选择Sencha Touch和jQuery Mobile
- Python-语句结构
- Halcon/MFC混合编程入门
- java list map 效率_遍历Map和List的几种方法和性能比较
- Zabbix Server 5.2安装教程
- 什么软件能测试太阳光照周期,你做的是UV测试,还是太阳光照测试?
- python arduino小车,搭建ROS小车底盘-第六篇ros_arduino_bridge功能包的使用
- 服务器里面增加单页网站,如何设计完美的单页网站
- 数据库设计遵循的原则
- 计算机应用能力考试ppt2003,[全国专业技术人员计算机应用能力考试PPT2003题库版.doc...
- Hexo之静态+动态背景设置
- 安装ros系统出现 404 Not Found [IP: 91.189.91.38 80]
- 操作 Windows7 任务栏的快捷方式