1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java如何取到配置文件中值 从配置文件中获取配置信息的几种方法

java如何取到配置文件中值 从配置文件中获取配置信息的几种方法

时间:2024-01-03 02:13:21

相关推荐

java如何取到配置文件中值 从配置文件中获取配置信息的几种方法

1、利用ResourceBundle类从properties文件中获取配置信息

创建配置文件并写入配置信息

image.png

使用以下代码可以轻松获取配置信息

package com.course.httpclient.cookies;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.util.EntityUtils;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.Test;

import java.io.IOException;

import java.util.Locale;

import java.util.ResourceBundle;

public class MyCookiesForGet {

//定义一个String属性,用来存储获取到的url信息

private String url;

//定义一个ResourceBundle类的对象,用来从application.properties文件中获取配置信息

private ResourceBundle resourceBundle;

@BeforeTest

public void BeforeTest(){

//调用getBundle方法,告诉resourceBundle从哪个配置文件中获取配置信息,定义Locale.CHINA是中文信息

resourceBundle=ResourceBundle.getBundle("application", Locale.CHINA);

//传入test.url配置名称,获取配置信息并赋值给url

url=resourceBundle.getString("test.url");

}

@Test

public void testGetCookies() throws IOException {

//拼接url

String uri=url+resourceBundle.getString("getcookies");

//httpclient请求接口获取返回结果并打印

HttpClient httpClient=new DefaultHttpClient();

HttpGet httpGet=new HttpGet(uri);

HttpResponse response=httpClient.execute(httpGet);

String result= EntityUtils.toString(response.getEntity());

System.out.println(result);

}

}

2、利用SpringBoot获取properties或yaml文件中的配置信息

配置文件的名称一定要写成application,或者写成application-prod,application-dev,通过- 横杠带后缀的方式。

比如这样写:

image.png

application.yaml中写的是:

spring:

profiles:

active: prod

datasource:

driver-class-name: com.mysql.cj.jdbc.Driver

url: jdbc:mysql://localhost:3306/dbgirl?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8

username: username

password: password

jpa:

hibernate:

ddl-auto: update

show-sql: true

该文件的名称一定要写成application才能从该文件中获取配置信息

通过active: prod来区分是哪个配置文件,哪个环境,目前是生产环境,配置成active:dev就是开发环境

datasource的配置是数据库的信息

jpa的配置是jpa插件,连接数据库会用到

看application-prod.yaml中写的内容:

server:

port : 8081 #端口号

servlet:

context-path: /test #请求路径

cupSize: B

age: 18

content: "cupSize:${cupSize}+age:${age}" #注解里面使用注解

girl:

cupSize : B

age : 22

从该文件中读取server的端口号和路径、参数信息

2.1 以下代码是用@value注解从配置文件中获取配置信息

package com.imooc.controller;

import com.imooc.properties.GirlProperties;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

@RestController

@RequestMapping(value = "/testtwo") //写到类前面,controller类中的每个方法请求时url都要加上/testtwo

public class HelloController {

//使用value注解把cupSize的参数值从yaml文件中获取过来,然后赋值给cupSize参数

@Value("${cupSize}")

private String cupSize;

@Value("${age}")

private String age;

//请求方式注解,value是指请求路径,method是请求方法

//value = {"/hello","/hi"} 是指请求url时用/hello或者/hi都可以

@RequestMapping(value = {"/hello","/hi"},method = RequestMethod.GET)

public String say(){

return cupSize+" "+age;

}

}

2.2以下代码是在配置文件中写组合配置参数:

配置文件中这样写:

image.png

代码中这些写:

package com.imooc.controller;

import com.imooc.properties.GirlProperties;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

@RestController

@RequestMapping(value = "/testtwo") //写到类前面,controller类中的每个方法请求时url都要加上/testtwo

public class HelloController {

// //获取组合参数content的值赋值给content

@Value("${content}")

private String content;

//请求方式注解,value是指请求路径,method是请求方法

//value = {"/hello","/hi"} 是指请求url时用/hello或者/hi都可以

@RequestMapping(value = {"/hello","/hi"},method = RequestMethod.GET)

public String say(){

return content;

}

}

2.3以下代码是从配置文件中获取配置参数并转换成类的属性,然后设置get和set方法去调用

配置文件中这样写:

image.png

定义实体类,使用这两个注解:

@Component

//获取前缀是girl的配置信息

@ConfigurationProperties(prefix = "girl")

代码如下:

package com.imooc.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.ponent;

@Component

//获取前缀是girl的配置信息

@ConfigurationProperties(prefix = "girl")

public class GirlProperties {

private String cupSize;

private Integer age;

public String getCupSize() {

return cupSize;

}

public void setCupSize(String cupSize) {

this.cupSize = cupSize;

}

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

}

controller中使用@Autowired注解,把实体类注入到controller中,使用get方法获取参数值,代码如下:

package com.imooc.controller;

import com.imooc.properties.GirlProperties;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

@RestController

@RequestMapping(value = "/testtwo") //写到类前面,controller类中的每个方法请求时url都要加上/testtwo

public class HelloController {

//使用@Autowired自动注入函数

@Autowired

private GirlProperties girlProperties;

//请求方式注解,value是指请求路径,method是请求方法

//value = {"/hello","/hi"} 是指请求url时用/hello或者/hi都可以

@RequestMapping(value = {"/hello","/hi"},method = RequestMethod.GET)

public String say(){

return girlProperties.getCupSize()+girlProperties.getAge();

}

}

3、利用写工具类从yaml文件和properties文件中获取配置信息

先在resource中新建一个yaml的配置文件,写入一些内容

image.png

和一个properties的文件:

image.png

编写工具类代码:

package com.meituan.Util;

import org.yaml.snakeyaml.Yaml;

import java.io.*;

import java.util.Map;

import java.util.Properties;

/*

该类中封装了从yaml中获取配置信息和从properties中获取配置信息、修改配置信息3个方法

测试类中直接调用该方法传入key值就可以了。

*/

public class ElementSource {

private static String testdatayaml = "src/main/resources/testdata.yaml";

private static String testdataproperties = "src/main/resources/testdata.properties";

//从yaml文件中获取信息

public String getElementsource(String name){

try {

Yaml yaml = new Yaml();

Map map;

map = (Map) yaml.load(new FileInputStream(testdatayaml));

if (map == null){

return null;

}else if (map.get(name) == null){

return null;

}else {

String resource = map.get(name).toString();

return resource;

}

}catch (Exception e){

e.printStackTrace();

return null;

}

}

//从properties配置文件中获取配置信息,其实不用写这个工具类,直接利用resourcebundle就可以直接获取配置信息

public String getproelementsource(String keyname){

Properties properties = new Properties();

try{

InputStream inputStream = new FileInputStream(testdataproperties);

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));

properties.load(bufferedReader);

inputStream.close();

}catch (Exception e){

e.printStackTrace();

}

if (properties.containsKey(keyname)){

return properties.getProperty(keyname);

}else {

System.out.println("获取的值不存在");

return null;

}

}

//根据某个key值修改properties配置文件中的value值

public void setproelementsource(String keyname,String value ){

try{

//重新new一个properties

Properties properties = new Properties();

//要先创建一个inputstream的流,把文件中的内容赋予给properties,要不然properties的内容就是null,就会导致修改时把之前的内容覆盖

InputStream inputStream = new FileInputStream(testdataproperties);

properties.load(inputStream);

//要关闭inputstream流

inputStream.close();

//创建输出流

OutputStream outputStream = new FileOutputStream(testdataproperties);

//创建bufferwriter 写入数据

BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"utf-8"));

//往配置文件中写入数据,如果没有对应的key值则新增,如果有就修改

properties.setProperty(keyname,value);

//添加注释信息

properties.store(bufferedWriter,keyname+" "+value);

//关闭bufferwriter

bufferedWriter.close();

//关闭outputstream流

outputStream.close();

}catch (Exception e){

e.printStackTrace();

}

}

}

测试类中直接调用该方法传入key值即可从配置文件中获取数据信息和修改数据信息。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。