1、使用@Value注解读取

读取properties配置文件时,默认读取的是application.properties。

application.properties:

demo.name=Name

demo.age=18

Java代码:

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

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

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

@RestController

public class GatewayController {

@Value("${demo.name}")

private String name;

@Value("${demo.age}")

private String age;

@RequestMapping(value = "/gateway")

public String gateway() {

return "get properties value by ''@Value'' :" +

//1、使用@Value注解读取

" name=" + name +

" , age=" + age;

}

}

运行结果:

这里,如果要把

@Value("${demo.name}")

private String name;

@Value("${demo.age}")

private String age;

部分放到一个单独的类A中进行读取,然后在类B中调用,则要把类A增加@Component注解,并在类B中使用@Autowired自动装配类A,代码如下。

类A:

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

import org.springframework.stereotype.Component;

@Component

public class ConfigBeanValue {

@Value("${demo.name}")

public String name;

@Value("${demo.age}")

public String age;

}

类B:

import cn.wbnull.springbootdemo.config.ConfigBeanValue;

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

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

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

@RestController

public class GatewayController {

@Autowired

private ConfigBeanValue configBeanValue;

@RequestMapping(value = "/gateway")

public String gateway() {

return "get properties value by ''@Value'' :" +

//1、使用@Value注解读取

" name=" + configBeanValue.name +

" , age=" + configBeanValue.age;

}

}

运行结果:

注意:如果@Value${}所包含的键名在application.properties配置文件中不存在的话,会抛出异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configBeanValue': Injection of autowired dependencies failed;

nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'demo.name' in value "${demo.name}"

2、使用Environment读取

application.properties:

demo.sex=男

demo.address=山东

代码

import cn.wbnull.springbootdemo.config.ConfigBeanValue;

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

import org.springframework.core.env.Environment;

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

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

@RestController

public class GatewayController {

@Autowired

private ConfigBeanValue configBeanValue;

@Autowired

private Environment environment;

@RequestMapping(value = "/gateway")

public String gateway() {

return "get properties value by ''@Value'' :" +

//1、使用@Value注解读取

" name=" + configBeanValue.name +

" , age=" + configBeanValue.age +

"

get properties value by ''Environment'' :" +

//2、使用Environment读取

" , sex=" + environment.getProperty("demo.sex") +

" , address=" + environment.getProperty("demo.address");

}

}

运行结果:

这里,我们在application.properties做如下配置:

server.tomcat.uri-encoding=UTF-8

spring.http.encoding.charset=UTF-8

spring.http.encoding.enabled=true

spring.http.encoding.force=true

spring.messages.encoding=UTF-8

重新运行结果如下:

3、使用@ConfigurationProperties注解读取

在实际项目中,当项目需要注入的变量值很多时,上述所述的两种方法工作量会变得比较大,这时候我们通常使用基于类型安全的配置方式,将properties属性和一个Bean关联在一起,即使用注解@ConfigurationProperties读取配置文件数据。

在src\main\resources下新建config.properties配置文件:

demo.phone=10086

demo.wife=self

创建ConfigBeanProp并注入config.properties中的值:

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

import org.springframework.context.annotation.PropertySource;

import org.springframework.stereotype.Component;

@Component

@ConfigurationProperties(prefix = "demo")

@PropertySource(value = "config.properties")

public class ConfigBeanProp {

private String phone;

private String wife;

public String getPhone() {

return phone;

}

public void setPhone(String phone) {

this.phone = phone;

}

public String getWife() {

return wife;

}

public void setWife(String wife) {

this.wife = wife;

}

}

@Component 表示将该类标识为Bean

@ConfigurationProperties(prefix = "demo")用于绑定属性,其中prefix表示所绑定的属性的前缀。

@PropertySource(value = "config.properties")表示配置文件路径。

使用时,先使用@Autowired自动装载ConfigBeanProp,然后再进行取值,示例如下:

import cn.wbnull.springbootdemo.config.ConfigBeanProp;

import cn.wbnull.springbootdemo.config.ConfigBeanValue;

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

import org.springframework.core.env.Environment;

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

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

@RestController

public class GatewayController {

@Autowired

private ConfigBeanValue configBeanValue;

@Autowired

private Environment environment;

@Autowired

private ConfigBeanProp configBeanProp;

@RequestMapping(value = "/gateway")

public String gateway() {

return "get properties value by ''@Value'' :" +

//1、使用@Value注解读取

" name=" + configBeanValue.name +

" , age=" + configBeanValue.age +

"

get properties value by ''Environment'' :" +

//2、使用Environment读取

" sex=" + environment.getProperty("demo.sex") +

" , address=" + environment.getProperty("demo.address") +

"

get properties value by ''@ConfigurationProperties'' :" +

//3、使用@ConfigurationProperties注解读取

" phone=" + configBeanProp.getPhone() +

" , wife=" + configBeanProp.getWife();

}

}

运行结果:

4.使用PropertiesLoaderUtils

app-config.properties

#### 通过注册监听器(`Listeners`) + `PropertiesLoaderUtils`的方式

com.zyd.type=Springboot - Listeners

com.zyd.title=使用Listeners + PropertiesLoaderUtils获取配置文件

com.zyd.name=zyd

com.zyd.address=Beijing

com.zyd.company=in

PropertiesListener.java 用来初始化加载配置文件

package com.zyd.property.listener;

import org.springframework.boot.context.event.ApplicationStartedEvent;

import org.springframework.context.ApplicationListener;

import com.zyd.property.config.PropertiesListenerConfig;

/**

* 配置文件监听器,用来加载自定义配置文件

*

* @authoryadong.zhang* @date 2017年6月1日 下午3:38:25

* @version V1.0

* @since JDK : 1.7

*/

public class PropertiesListener implements ApplicationListener{

private String propertyFileName;

public PropertiesListener(String propertyFileName) {

this.propertyFileName = propertyFileName;

}

@Override

public void onApplicationEvent(ApplicationStartedEvent event) {

PropertiesListenerConfig.loadAllProperties(propertyFileName);

}

}

PropertiesListenerConfig.java 加载配置文件内容

package com.zyd.property.config;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.util.HashMap;

import java.util.Map;

import java.util.Properties;

import org.springframework.beans.BeansException;

import org.springframework.core.io.support.PropertiesLoaderUtils;

/**

* 第四种方式:PropertiesLoaderUtils

*

* @authoryadong.zhang* @date 2017年6月1日 下午3:32:37

* @version V1.0

* @since JDK : 1.7

*/

public class PropertiesListenerConfig {

public static Map propertiesMap = new HashMap<>();

private static void processProperties(Properties props) throws BeansException {

propertiesMap = new HashMap();

for (Object key : props.keySet()) {

String keyStr = key.toString();

try {

// PropertiesLoaderUtils的默认编码是ISO-8859-1,在这里转码一下

propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes("ISO-8859-1"), "utf-8"));

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} catch (java.lang.Exception e) {

e.printStackTrace();

}

}

}

public static void loadAllProperties(String propertyFileName) {

try {

Properties properties = PropertiesLoaderUtils.loadAllProperties(propertyFileName);

processProperties(properties);

} catch (IOException e) {

e.printStackTrace();

}

}

public static String getProperty(String name) {

return propertiesMap.get(name).toString();

}

public static MapgetAllProperty() {

return propertiesMap;

}

}

Applaction.java 启动类

package com.zyd.property;

import java.io.UnsupportedEncodingException;

import java.util.HashMap;

import java.util.Map;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

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

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

import com.zyd.property.config.PropertiesListenerConfig;

import com.zyd.property.listener.PropertiesListener;

/**

* @authoryadong.zhang* @date 2017年6月1日 下午3:49:30

* @version V1.0

* @since JDK : 1.7

*/

@SpringBootApplication

@RestController

public class Applaction {

/**

*

* 第四种方式:通过注册监听器(`Listeners`) + `PropertiesLoaderUtils`的方式

*

* @author zyd

* @throws UnsupportedEncodingException

* @since JDK 1.7

*/

@RequestMapping("/listener")

public Maplistener() {

Map map = new HashMap();

map.putAll(PropertiesListenerConfig.getAllProperty());

return map;

}

public static void main(String[] args) throws Exception {

SpringApplication application = new SpringApplication(Applaction.class);

// 第四种方式:注册监听器

application.addListeners(new PropertiesListener("app-config.properties"));

application.run(args);

}

}

java通过spring获取配置文件_springboot获取properties文件的配置内容(转载)相关推荐

  1. spring核心配置文件引入外部properties文件和另外的xml配置文件

    spring核心配置文件引入外部properties文件和另外的xml配置文件 为什么要引入外部文件 我们使用jdbc的时候,会创建一个jdbc.properties配置文件,如果我需要在spring ...

  2. java读取mysql数据库配置文件_java读取properties文件的方法

    Java 读写Properties配置文件 Java 读写Properties配置文件 1.Properties类与Properties配置文件 Properties类继承自Hashtable类并且实 ...

  3. 使用spring最简单地读取properties文件中的内容

    相比传统的读取propertis文件内容,使用spring框架会更加简单快捷 1. 第一步,在spring的配置文件中,将propertis文件加载到spring容器 2. 加载了配置文件后,只需要在 ...

  4. Spring读取配置文件,获取bean的几种方式

    Spring读取配置文件,获取bean的几种方式 方法一:在初始化时保存ApplicationContext对象 代码: ApplicationContext ac = new FileSystemX ...

  5. 使用java代码获取yml及properties文件中的内容,获取值

    获取properties文件中的内容 最近做项目一些值需要放在配置文件中,一开始使用的是properties文件,我这里没有使用注解@Value获取. 获取: InputStream in = Mes ...

  6. Idea Spring Boot配置文件.yaml或.properties不能自动提示的有效解决办法

    SpringBoot项目的配置文件.yaml/.yml/.properties文件编写的时候没有自动提示,网上的解决办法五花八门,不一定适合具体个人的IDE环境,下面总结一套能解决绝大部分情况的方案: ...

  7. Spring配置文件中引入properties文件

    jdbc.properties文件中有信息如下: username=root url=jdbc:mysql://localhost:3306/qw?characterEncoding=utf8 dri ...

  8. scala学习-12-scala读取java项目下Src目录下的properties文件

    1.概述 scala读取java项目下Src目录下的properties文件 package scalaimport java.util.Properties import java.io.FileI ...

  9. spring使用@Value注解读取.properties文件时出现中文乱码问题的解决

    spring使用@Value注解读取.properties文件时出现中文乱码问题的解决 参考文章: (1)spring使用@Value注解读取.properties文件时出现中文乱码问题的解决 (2) ...

最新文章

  1. NestedScrolling CoordinatorLayout
  2. ad18修改过孔和走线间距_Altium Designer设计PCB--如何设置铺铜与导线或过孔的间距...
  3. 【数据结构与算法】之深入解析“股票价格跨度”的求解思路与算法示例
  4. robot wireless communication
  5. 关于本Blog无法进行评论问题的说明
  6. Arrays 工具类
  7. 产生java的动态库文件so的配置步骤
  8. 苹果全面开放漏洞奖励计划:最高100万美元等你拿
  9. matlab 计算结果为nan,matlab 计算 结果总是为Nan
  10. C语言自学之路三(循环、选择、函数、数组)
  11. 【Tensorflow2.0】8、tensorflow2.0_hdf5_savedmodel_pb模型转换[1]
  12. LabVIEW编程LabVIEW控制GPS例程与相关资料
  13. 大数据核心技术是什么?
  14. SQLServer实现快速进行简繁体的翻译功能
  15. Facebok的动画框架pop
  16. cmd命令下修复硬盘/U盘
  17. 竖流式沉淀池三角堰计算_竖流式沉淀池设计计算
  18. STM32单片机开发应用教程 (HAL库版) ---基于国信长天嵌入式竞赛实训平台(CT117E-M4)教程汇总 与第一章 硬件平台简介
  19. c++ 静态成员函数和非静态成员函数的区别?
  20. 使用决策树对数据进行分类——识别橘子苹果

热门文章

  1. 丑憨批的爬虫笔记5信息标记与提取
  2. 安装service_identity失败总结
  3. Java RMI 多个JVM间相互通信
  4. 1333和1600能双通道吗_80后童年神作《光环致远星》steam解锁 ?你的电脑还OK吗?...
  5. jmeter生成优美的压力测试报告,jmeter生成html压测报告,jmeter压力测试
  6. 网易2022秋季校园招聘-通用技术A卷-0821
  7. 《软件工程》实验报告——软件设计
  8. Applese 的回文串
  9. shell的学习和命令使用入门
  10. ARKit从入门到精通(10)-ARKit让飞机绕着你飞起来