Spring boot @Value注解读取application.properties配置文件中的属性值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yaomingyang/article/details/82894188

@Value注解引用application.properties配置文件属性值

@Value 注解加载属性值的时候可以支持两种表达式来进行配置, 如下所示:

  • 一种是PlaceHolder 方式, 格式为${...}, 大括号内为PlaceHolder。
  • 另一种是使用SpEL 表达式(Spring Expression Language), 格式为#{...}, 大括号
    内为SpEL 表达式。
    示例代码如下:
package com.example.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWrold {

	@Value("${spring.application.name}")
	private String name;
	
	@RequestMapping("/hello")
	public String index() {
		return "hello world is beautify "+name;
	}
}

application.properties配置文件:

#server port
server.port=8080
#spring cloud name
spring.application.name=cloud

API返回的结果是:

hello world is beautify cloud

application.properties配置文件参数引用:

在application.properties 中的各个参数之间可以直接通过使用PlaceHolder 的方式来进行引用, 就像下面的设置:

  • book.name=SpringCloud
  • book.author=liming
  • book.desc= ${book.author} is writing《${book.name}》
  • book.desc 参数引用了上文中定义的book.name和book.author 属性, 最后该属性的值就是liming is writing《SpringCloud》。

猜你喜欢

转载自blog.csdn.net/yaomingyang/article/details/82894188