http://zetcode.com/springboot/configurationproperties/

Spring Boot @ConfigurationProperties教程展示了如何在 Spring Boot 应用中使用@ConfigurationProperties将属性绑定到对象。

Spring 是流行的 Java 应用框架,而 Spring Boot 是 Spring 的演进,可以帮助轻松地创建独立的,生产级的基于 Spring 的应用。

@ConfigurationProperties

@ConfigurationProperties允许轻松地将整个属性和 Yaml 文件映射到一个对象。 它还允许使用 JSR-303 bean 验证来验证属性。 默认情况下,注解从application.properties文件中读取。 可以使用@PropertySource注解来更改源文件。

Spring Boot @ConfigurationProperties示例

以下应用从application.properties文件读取配置数据,该文件是默认的 Spring Boot 配置文件。

  1. pom.xml
  2. src
  3. ├───main
  4. ├───java
  5. └───com
  6. └───zetcode
  7. Application.java
  8. MyRunner.java
  9. └───conf
  10. AppProperties.java
  11. └───resources
  12. application.properties
  13. └───test
  14. └───java

这是项目结构。

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <groupId>com.zetcode</groupId>
  8. <artifactId>springbootconfigurationproperties</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>jar</packaging>
  11. <properties>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. <maven.compiler.source>11</maven.compiler.source>
  14. <maven.compiler.target>11</maven.compiler.target>
  15. </properties>
  16. <parent>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-parent</artifactId>
  19. <version>2.1.1.RELEASE</version>
  20. </parent>
  21. <dependencies>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter</artifactId>
  25. </dependency>
  26. </dependencies>
  27. <build>
  28. <plugins>
  29. <plugin>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-maven-plugin</artifactId>
  32. </plugin>
  33. </plugins>
  34. </build>
  35. </project>

这是 Maven pom.xml文件。

resources/application.properties

  1. spring.main.banner-mode=off
  2. app.colour=steelblue
  3. app.lang=en
  4. app.theme=dark

application.properties文件中,我们具有三个自定义属性。 它们具有app前缀。

com/zetcode/conf/AppProperties.java

  1. package com.zetcode.conf;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import org.springframework.context.annotation.Configuration;
  4. @Configuration
  5. @ConfigurationProperties(prefix = "app")
  6. public class AppProperties {
  7. private String colour;
  8. private String lang;
  9. private String theme;
  10. public String getColour() {
  11. return colour;
  12. }
  13. public void setColour(String colour) {
  14. this.colour = colour;
  15. }
  16. public String getLang() {
  17. return lang;
  18. }
  19. public void setLang(String lang) {
  20. this.lang = lang;
  21. }
  22. public String getTheme() {
  23. return theme;
  24. }
  25. public void setTheme(String theme) {
  26. this.theme = theme;
  27. }
  28. }

这些属性将绑定到此配置对象。

  1. @Configuration
  2. @ConfigurationProperties(prefix = "app")
  3. public class AppProperties {

@Configuration注解使它成为 Spring 管理的 bean。 在@ConfigurationProperties中,我们为属性设置前缀。

com/zetcode/MyRunner.java

  1. package com.zetcode;
  2. import com.zetcode.conf.AppProperties;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.CommandLineRunner;
  7. import org.springframework.stereotype.Component;
  8. @Component
  9. public class MyRunner implements CommandLineRunner {
  10. private static final Logger logger = LoggerFactory.getLogger(Application.class);
  11. @Autowired
  12. private AppProperties appProperties;
  13. @Override
  14. public void run(String... args) throws Exception {
  15. logger.info("Colour: {}", appProperties.getColour());
  16. logger.info("Language: {}", appProperties.getLang());
  17. logger.info("Theme: {}", appProperties.getTheme());
  18. }
  19. }

MyRunner中,我们将AppProperties注入字段中并读取其值。

com/zetcode/Application.java

  1. package com.zetcode;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class Application {
  6. public static void main(String[] args) {
  7. SpringApplication.run(Application.class, args);
  8. }
  9. }

Application是设置 Spring Boot 应用的入口。

Spring Boot @ConfigurationProperties示例 II

在第二个应用中,我们还将验证属性。

  1. pom.xml
  2. src
  3. ├───main
  4. ├───java
  5. └───com
  6. └───zetcode
  7. Application.java
  8. MyRunner.java
  9. └───config
  10. MailProperties.java
  11. └───resources
  12. application.properties
  13. mail.properties
  14. └───test
  15. └───java

这是项目结构。

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <groupId>com.zetcode</groupId>
  8. <artifactId>springbootconfigurationpropertiesvalidation</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>jar</packaging>
  11. <properties>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. <maven.compiler.source>11</maven.compiler.source>
  14. <maven.compiler.target>11</maven.compiler.target>
  15. </properties>
  16. <parent>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-parent</artifactId>
  19. <version>2.1.1.RELEASE</version>
  20. </parent>
  21. <dependencies>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter</artifactId>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.hibernate.validator</groupId>
  28. <artifactId>hibernate-validator</artifactId>
  29. </dependency>
  30. </dependencies>
  31. <build>
  32. <plugins>
  33. <plugin>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-maven-plugin</artifactId>
  36. </plugin>
  37. </plugins>
  38. </build>
  39. </project>

这是pom.xml文件。 我们还有一个hibernate-validator依赖项。

resources/application.properties

  1. spring.main.banner-mode=off

这是application.properties文件。

resources/mail.properties

  1. hostname=info@example.com
  2. port=9000
  3. from=admin@example.com
  4. recipients[0]=user1@example.com
  5. recipients[1]=user2@example.com
  6. recipients[2]=user3@example.com
  7. recipients[3]=user4@example.com

我们有一个自定义的mail.properties文件。

com/zetcode/config/MailProperties.java

  1. package com.zetcode.config;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.context.annotation.PropertySource;
  5. import org.springframework.validation.annotation.Validated;
  6. import javax.validation.constraints.Max;
  7. import javax.validation.constraints.Min;
  8. import javax.validation.constraints.NotNull;
  9. import java.util.List;
  10. @Configuration
  11. @PropertySource("classpath:mail.properties")
  12. @ConfigurationProperties
  13. @Validated
  14. public class MailProperties {
  15. @NotNull
  16. private String hostname;
  17. @Min(1000)
  18. @Max(10000)
  19. private int port;
  20. @NotNull
  21. private String from;
  22. @NotNull
  23. private List<String> recipients;
  24. public String getHostname() {
  25. return hostname;
  26. }
  27. public void setHostname(String hostname) {
  28. this.hostname = hostname;
  29. }
  30. public int getPort() {
  31. return port;
  32. }
  33. public void setPort(int port) {
  34. this.port = port;
  35. }
  36. public String getFrom() {
  37. return from;
  38. }
  39. public void setFrom(String from) {
  40. this.from = from;
  41. }
  42. public List<String> getRecipients() {
  43. return recipients;
  44. }
  45. public void setRecipients(List<String> recipients) {
  46. this.recipients = recipients;
  47. }
  48. }

我们使用@PropertySource注解设置自定义属性文件的路径。 @Validated注解验证属性。

com/zetcode/MyRunner.java

  1. package com.zetcode;
  2. import com.zetcode.config.MailProperties;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.CommandLineRunner;
  7. import org.springframework.stereotype.Component;
  8. @Component
  9. public class MyRunner implements CommandLineRunner {
  10. private static final Logger logger = LoggerFactory.getLogger(Application.class);
  11. @Autowired
  12. private MailProperties mailProperties;
  13. @Override
  14. public void run(String... args) throws Exception {
  15. logger.info("Hostname: {}", mailProperties.getHostname());
  16. logger.info("Port: {}", mailProperties.getPort());
  17. logger.info("From: {}", mailProperties.getFrom());
  18. logger.info("Recipients: {}", mailProperties.getRecipients());
  19. }
  20. }

我们注入MailProperties并以run()方法读取它们。

com/zetcode/Application.java

  1. package com.zetcode;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class Application {
  6. public static void main(String[] args) {
  7. SpringApplication.run(Application.class, args);
  8. }
  9. }

这是Application类。

我们使用mvn -q spring-boot:run运行该应用。

在本教程中,我们展示了如何使用@ConfigurationProperties从外部文件读取配置属性。 您可能也对相关教程感兴趣: Spring PropertySource教程Spring Boot CommandLineRunner教程Java 教程或列出所有 Spring Boot 教程