【Spring Boot】Spring Boot @ConfigurationProperties示例 | 读取自定义配置文件信息
文章目录
Spring Boot
@ConfigurationProperties
是用于外部化配置的注解。
为了将属性文件中的属性值注入到一个类中,我们可以在类的层面上添加@ConfigurationProperties
与原型注释(如@Componen
t),或者在@Configuration
类中的@Bean
方法中添加@ConfigurationProperties
。
@ConfigurationProperties
用于绑定和验证来自属性文件(如.properties
文件)的外部属性。
@ConfigurationProperties
有以下可选元素:
ignoreInvalidFields: 忽略无效字段的布尔值。
ignoreUnknownFields: 忽略未知字段的布尔值。
prefix: 要绑定到此对象的属性的前缀。
value: 要绑定到此对象的属性的前缀。
为了使用@ConfigurationProperties
从属性文件注入值,我们的类必须创建类属性的setter
方法。在这里,我们将详细讨论使用@ConfigurationProperties
并举例说明。
示例工具版本
- Java 11
- Spring 5.1.7.RELEASE
- Spring Boot 2.1.5.RELEASE
- Hibernate Validator 6.0.16
- Maven 3.5.2
使用 @ConfigurationProperties 的步骤
找到使用@ConfigurationProperties
注解的步骤。
1. 创建一个带有@ConfigurationProperties
和@Component
注释的类。在这里,我们的类中有字符串和整数属性。
Team.java
package com.concretepage;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties
public class Team {
private String team;
private int teamSize;
private String teamLeader;
//Setters and Getters
public String toString() {
return "Team:" + team + " - " + teamSize + " - " + teamLeader;
}
}
创建类字段的setter
方法是使用@ConfigurationProperties
的必要条件。
2. 多个单词的属性名称如teamSize
可以在属性文件中绑定属性名称如teamSize
或team-size
或team_size
。找到属性文件。
myteam.properties
team=XYZ Team
team-size=3
team-leader=Mahesh
3. 在配置类中,使用@PropertySource
注解导入.property
文件。
AppConfig.java
package com.concretepage;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:myteam.properties")
public class AppConfig {
}
所有上述属性值都将绑定到Team
类,相应地,我们可以根据需要将这个类注入到任何其他类并获取值。
4. 现在运行该应用程序。
MySpringBootApp.java
package com.concretepage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class MySpringBootApp {
public static void main(String[] args) {
final ApplicationContext ctx = SpringApplication.run(MySpringBootApp.class, args);
final Team team = ctx.getBean(Team.class);
System.out.println("--- Team ---");
System.out.println(team);
}
}
输出
--- Team ---
Team:XYZ Team - 3 - Mahesh
使用 @ConfigurationProperties 的前缀
我们可以在@ConfigurationProperties
注解中使用前缀元素。如果属性文件的属性以前缀开始,就可以在@ConfigurationProperties
中进行配置。找到属性文件。
myteam.properties
app.team=XYZ Team
app.team-size=3
app.team-leader=Mahesh
我们可以看到,属性已经以前缀app
字开头。我们需要在@ConfigurationProperties
中对其进行配置,将这些值注入到Team
类中。
Team.java
@Component
@ConfigurationProperties(prefix="app")
public class Team {
private String team;
private int teamSize;
private String teamLeader;
//Setters and Getters
public String toString() {
return "Team:" + team + " - " + teamSize + " - " + teamLeader;
}
}
使用 @ConfigurationProperties 与 @Bean 一起使用
我们可以将@ConfigurationProperties
与@Bean
以及@Component
注解一起使用。
在上面的例子中,我们已经将@ConfigurationProperties
与@Component
一起使用。
这里我们将创建一个例子来使用@ConfigurationProperties
和@Bean
。
我们需要在方法层面上使用@ConfigurationProperties
和@Bean
。找到这个例子。
AppConfig.java
package com.concretepage;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource({"classpath:myteam.properties", "classpath:project-util.properties"})
public class AppConfig {
@Bean
@ConfigurationProperties(prefix="project")
public Project getProject() {
return new Project();
}
}
Project.java
package com.concretepage;
public class Project {
private String projectName;
private int size;
private String manager;
//Setters and getters
public String toString() {
return "Project:" + projectName + " - " + size + " - " + manager;
}
}
project-util.properties
project.project-name=PQR Project
project.size=10
project.manager=John
使用 @ConfigurationProperties 与Object, List, Map 和 Array 属性
在上面的例子中,我们已经看到了如何将简单的属性与一个类绑定。
现在我们将提供使用@ConfigurationProperties
绑定Object
、List
、Map
和Array
属性的例子。
myteam.properties
app.team=XYZ Team
app.team-size=3
app.team-leader=Mahesh
#Object properties
app.company.name=ABC Ltd
app.company.ceo=Narendra
app.company.location=Delhi
#List properties
app.employees[0].name=Amar
app.employees[0].designation=Developer
app.employees[0].age=25
app.employees[1].name=Akbar
app.employees[1].designation=Tester
app.employees[1].age=23
app.employees[2].name=Anthony
app.employees[2].designation=Designer
app.employees[2].age=27
#Map Properties
app.technologies.BACKEND=Java
app.technologies.FRONTEND=Angular
app.technologies.DATABASE=Oracle
#Array Properties
app.clients[0]=A Client
app.clients[1]=B Client
app.clients[2]=C Client
AppConfig.java
@Configuration
@PropertySource({"classpath:myteam.properties", "classpath:project-util.properties"})
public class AppConfig {
------
}
Team.java
@Component
@ConfigurationProperties(prefix="app")
public class Team {
private String team;
private int teamSize;
private String teamLeader;
private Company company;
private List<Employee> employees;
private Map<String, String> technologies;
private String[] clients;
//Setters and Getters
public String toString() {
return "Team:" + team + " - " + teamSize + " - " + teamLeader;
}
}
1. Object Properties
myteam.properties
#Object properties
app.company.name=ABC Ltd
app.company.ceo=Narendra
app.company.location=Delhi
Team.java
@Component
@ConfigurationProperties(prefix="app")
public class Team {
------
private Company company;
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
------
}
Company.java
package com.concretepage;
public class Company {
private String name;
private String ceo;
private String location;
//Setters and Getters
public String toString() {
return "Company:" + name + " - " + ceo + " - " + location;
}
}
2. List Properties
myteam.properties
#List properties
app.employees[0].name=Amar
app.employees[0].designation=Developer
app.employees[0].age=25
app.employees[1].name=Akbar
app.employees[1].designation=Tester
app.employees[1].age=23
app.employees[2].name=Anthony
app.employees[2].designation=Designer
app.employees[2].age=27
Team.java
@Component
@ConfigurationProperties(prefix="app")
public class Team {
------
private List<Employee> employees;
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
------
}
Employee.java
package com.concretepage;
public class Employee {
private String name;
private String designation;
private int age;
//Setters and Getters
public String toString() {
return "Employee:" + name + " - " + designation + " - " + age;
}
}
3. Map Properties
myteam.properties
#Map Properties
app.technologies.BACKEND=Java
app.technologies.FRONTEND=Angular
app.technologies.DATABASE=Oracle
Team.java
@Component
@ConfigurationProperties(prefix="app")
public class Team {
------
private Map<String, String> technologies;
public Map<String, String> getTechnologies() {
return technologies;
}
public void setTechnologies(Map<String, String> technologies) {
this.technologies = technologies;
}
------
}
4. Array Properties
myteam.properties
#Array Properties
app.clients[0]=A Client
app.clients[1]=B Client
app.clients[2]=C Client
Team.java
@Component
@ConfigurationProperties(prefix="app")
public class Team {
------
private String[] clients;
public String[] getClients() {
return clients;
}
public void setClients(String[] clients) {
this.clients = clients;
}
------
}
输出效果
现在让我们运行演示应用程序。
MySpringBootApp.java
package com.concretepage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class MySpringBootApp {
public static void main(String[] args) {
final ApplicationContext ctx = SpringApplication.run(MySpringBootApp.class, args);
final Team team = ctx.getBean(Team.class);
System.out.println("--- Team ---");
System.out.println(team);
System.out.println("--- Team Employee---");
team.getEmployees().forEach(e -> System.out.println(e));
System.out.println("--- Technologies ---");
System.out.println(team.getTechnologies().size());
team.getTechnologies().forEach(((t, v) -> System.out.println(t + " - " + v)));
System.out.println("--- Company ---");
System.out.println(team.getCompany());
System.out.println("--- Clients ---");
for (String c : team.getClients()) {
System.out.println(c);
}
System.out.println("--- Project ---");
final Project project = ctx.getBean(Project.class);
System.out.println(project);
}
}
输出
--- Team ---
Team:XYZ Team - 3 - Mahesh
--- Team Employee---
Employee:Amar - Developer - 25
Employee:Akbar - Tester - 23
Employee:Anthony - Designer - 27
--- Technologies ---
3
FRONTEND - Angular
DATABASE - Oracle
BACKEND - Java
--- Company ---
Company:ABC Ltd - Narendra - Delhi
--- Clients ---
A Client
B Client
C Client
--- Project ---
Project:PQR Project - 10 - John
使用 @ConfigurationProperties 与 @EnableConfigurationProperties
假设我们有一个用@ConfigurationProperties
注解的类,但它没有用@Component
注解,或者它不是一个Spring bean
。
在这种情况下,为了使用@ConfigurationProperties
从属性文件中注入值,我们将@EnableConfigurationProperties
注解与@SpringBootApplication
一起使用,并将@ConfigurationProperties
注解的类指定为@EnableConfigurationProperties
。
找到这个例子。这里我们从Team.java
中删除了@Component
。
Team.java
@ConfigurationProperties(prefix="app")
public class Team {
private String team;
private int teamSize;
private String teamLeader;
private Company company;
private List<Employee> employees;
private Map<String, String> technologies;
private String[] clients;
//Setters and Getters
public String toString() {
return "Team:" + team + " - " + teamSize + " - " + teamLeader;
}
}
现在要启用@ConfigurationProperties
的工作,我们需要使用@EnableConfigurationProperties
注解与@SpringBootApplication
结合起来,并指定上述类到其中。
MySpringBootApp.java
package com.concretepage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
@EnableConfigurationProperties(Team.class)
public class MySpringBootApp {
public static void main(String[] args) {
final ApplicationContext ctx = SpringApplication.run(MySpringBootApp.class, args);
------
}
}
使用 @Validated 和 @ConfigurationProperties
使用@ConfigurationProperties
从属性文件注入到类中的值可以用Spring
的@Validated
注解来验证。
Team.java
package com.concretepage;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
@Component
@ConfigurationProperties(prefix="app")
@Validated
public class Team {
@NotBlank
private String team;
@NumberFormat
private int teamSize;
@Size(max=30)
private String teamLeader;
@NotNull
private Company company;
@NotEmpty
private List<Employee> employees;
@NotEmpty
private Map<String, String> technologies;
private String[] clients;
//Setters and Getters
public String toString() {
return "Team:" + team + " - " + teamSize + " - " + teamLeader;
}
}
Maven
找到我们示例中使用的Maven
配置。
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath />
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
</dependencies>
YAML 文件
找到与示例中使用的属性文件等效的YAML
文件。
application.yml
app:
team:XYZ Team
team-size:3
team-leader:Mahesh
employees:
- name:Amar
designation:Developer
age:25
- name:Akbar
designation:Tester
age:23
- name:Anthony
designation:Designer
age:27
technologies:
BACKEND:Java
FRONTEND:Angular
DATABASE:Oracle
clients:
- A Client
- B Client
- C Client
company:
name:ABC Ltd
ceo:Narendra
location:Delhi
project:
project-name:PQR Project
size:10
manager:John
参考文献
【1】Spring @ConfigurationProperties Doc
【2】Spring Boot @ConfigurationProperties Example
源码下载
下一篇: Agc019_F Yes or No