Spring Boot 中读取配置属性的几种方式

本文详细介绍了在Spring Boot中读取配置属性的四种方法:@Value注解、Environment对象、@ConfigurationProperties和PropertiesLoaderUtils。通过实例展示了如何使用这些方法从配置文件中获取属性值。
摘要由CSDN通过智能技术生成

前言

  本文介绍Spring Boot中读取配置属性的几种方式,项目示例中用到的application.ymlapplication.properties定义如下:

application.yml

application.properties

@Value

  @Value是比较常见的注入方式,功能强大但一般可读性较差。

    @Value("str")
    private String str; // 注入普通字符串
	
    @Value("${hello}")
    private String hello; // 注入配置属性

    @Value("#{systemProperties['os.name']}")
    private String systemPropertiesName; // 注入操作系统属性

    @Value("#{ T(java.lang.Math).random() * 100.0 }")
    private double randomNumber; //注入表达式结果

    @Value("#{userBean.name}")
    private String name; // 注入Bean属性

  下面通过@Value注解获取定义在配置文件的属性值:

	@SpringBootApplication
	public class AttributeApplication {
   

		private static final String SPRING_BOOT_HELLO = "spring-boot.hello";

		@Value("${" + SPRING_BOOT_HELLO + "}")
		private String hello;

		/**
		 * 1. 通过@Value注解获取值
		 */
		public void getAttrByValueAnnotation() {
   
			System.out.println("1. 通过@Value注解获取值: " + hello);
		}

		public static void main(String[] args) {
   
			ConfigurableApplicationContext applicationContext = SpringApplication.run(AttributeApplication.class, args);
			AttributeApplication bean = applicationContext.getBean(AttributeApplication.class);
			bean.getAttrByValueAnnotation
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值