gpt4 book ai didi

Spring Boot @ConfigurationProperties注解使用示例

转载 作者:知者 更新时间:2024-03-12 08:01:10 24 4
gpt4 key购买 nike

Spring Boot @ConfigurationProperties 是外部化配置的注解。要将属性值从属性文件注入到类中,我们可以在类级别添加 @ConfigurationProperties,并使用诸如 @Component 之类的构造型注解,或者将 @ConfigurationProperties 添加到 @Configuration 类中的 @Bean 方法中。 @ConfigurationProperties 用于绑定和验证来自属性文件(如 .properties 文件)的外部属性。 @ConfigurationProperties 具有以下可选元素。
ignoreInvalidFields:忽略无效字段的布尔值。
ignoreUnknownFields:忽略未知字段的布尔值。
prefix:绑定到此对象的属性的前缀。
value:绑定到此对象的属性的前缀。

要使用 @ConfigurationProperties 从属性文件中注入值,我们的类必须创建类属性的 setter 方法。在这里,我们将通过示例详细讨论使用 @ConfigurationProperties

使用@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等多个单词的属性名可以绑定属性文件中的teamSizeteam-sizeteam_size等属性名。找到属性文件。
myteam.properties

team=XYZ Team
team-size=3
team-leader=Mahesh

3. 在配置类中,使用 @PropertySource 注解导入 .properties 文件。
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 与对象、列表、映射和数组属性一起使用

在上面的示例中,我们已经看到了如何将简单属性与类绑定。现在我们将提供使用 @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。对象属性

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。列出属性

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属性

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。数组属性

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com