在Spring Boot中读取application.properties

  通过这篇简短的博客文章,我将与您分享一些可以从Spring Boot中的application.properties文件中读取应用程序属性的方法。 我将分享3种方式: 

  1. 使用 Environment 对象 读取application.properties , 
  2. 使用 @Value 注释 读取属性 。 
  3. 使用@ConfigurationProperties 从application.properties文件中读取属性 

创建Spring Boot项目时,您应该 在src / main / resources 文件夹中 创建 application.properties 文件 。 如果由于某种原因,在Spring Boot项目的src / main / resources文件夹中没有application.properties文件,则可以手动创建此文件。 

读application.properties使用环境 

最有可能从application.properties文件中读取属性的最简单方法之一是自动装配Environment对象。 您需要做的就是: 

1)使用@Autowired注释将Environment 对象注入Rest Controller或Service类,如下所示: 

@Autowired
private Environment env;

2)用户getProperty(String key)方法获取特定属性的值 。 喜欢这个: 
String keyValue = env.getProperty(key);
String keyValue = env.getProperty(key);

假设我在application.properties文件中有这些属性: 

app.title=Learning Spring Boot 
app.description=Working with properties file

我需要创建一个Web服务端点,它接受属性的键名作为请求参数并返回属性值。 

这是我的 Rest Controller类:

@RestController
@RequestMapping("app")
public class AppController {

@Autowired
private Environment env;

@GetMapping("/property")
public String getPropertyValue(@RequestParam("key") String key)
{
String returnValue = "No value";

String keyValue = env.getProperty(key);

if( keyValue!= null && !keyValue.isEmpty())
{
returnValue = keyValue;
}
return returnValue;
}
}

请注意,为了能够从application.properties文件中读取属性,我需要使用@Autowired注释来注入Environment对象。 然后我可以简单地调用它的getProperty(String key)方法来获取所请求属性的值。 

使用@Value Annotation读取属性 


另一种读取应用程序属性的非常简单的方法是使用@Value注释。 只需使用@Value注释对类字段进行注释,并提供要从application.properties文件和类字段变量中读取的属性的名称。 

要读取 app.title 属性 的值, 请 使用@Value注释注释类字段,如下所示: 
@Value("${app.title}")
private String appTitle;


假设我有以下application.properties文件: 
app.title=Learning Spring Boot 
app.description=Working with properties file

下面是Rest Controller的一个示例,它使用@Value批注来读取app.title属性。 


@RestController
@RequestMapping("app")

@Value("${app.title}")
private String appTitle;

@GetMapping("/value")
public String getValue()
{
return appTitle;
}
}

这就是我需要做的一切。 

使用@ConfigurationProperties读取应用程序属性 


在Spring Boot应用程序中读取应用程序属性的另一种方法是使用@ConfigurationProperties。 为此,我们需要创建一个Plain Old Java Object,其中每个类字段与属性文件中的键名称相匹配。 

例如,假设我们有相同的application.properties文件: 

app.title=Learning Spring Boot 
app.description=Working with properties file

因为每个属性名称都以 app 的前缀开头,所以 我们需要注释我们的Java Bean: 

@ConfigurationProperties("app")

以下是使用@ConfigurationProperties批注注释的Java类的示例: 

@Component
@ConfigurationProperties("app")
public class AppProperties {

private String title;
private String description;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}

}

要在Rest Controller或Service类中使用此类,我们只需使用@Autowired注释对其进行自动装配。 

一旦我们有了AppProperties类的实例,我们就可以使用getter来获取存储在application.properties文件中的属性的值。 

在Spring Boot应用程序中读取应用程序属性就是这三种非常简单的方法。 

 

 Spring Boot