# Spring Boot `@ConfigurationProperties`教程

> [http://zetcode.com/springboot/configurationproperties/](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 配置文件。

```java
pom.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           │   Application.java
│   │           │   MyRunner.java
│   │           └───conf
│   │                   AppProperties.java
│   └───resources
│           application.properties
└───test
    └───java

```

这是项目结构。

`pom.xml`

```java
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zetcode</groupId>
    <artifactId>springbootconfigurationproperties</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

```

这是 Maven `pom.xml`文件。

`resources/application.properties`

```java
spring.main.banner-mode=off

app.colour=steelblue
app.lang=en
app.theme=dark

```

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

`com/zetcode/conf/AppProperties.java`

```java
package com.zetcode.conf;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "app")
public class AppProperties {

    private String colour;
    private String lang;
    private String theme;

    public String getColour() {
        return colour;
    }

    public void setColour(String colour) {
        this.colour = colour;
    }

    public String getLang() {
        return lang;
    }

    public void setLang(String lang) {
        this.lang = lang;
    }

    public String getTheme() {
        return theme;
    }

    public void setTheme(String theme) {
        this.theme = theme;
    }
}

```

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

```java
@Configuration
@ConfigurationProperties(prefix = "app")
public class AppProperties {

```

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

`com/zetcode/MyRunner.java`

```java
package com.zetcode;

import com.zetcode.conf.AppProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyRunner implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    @Autowired
    private AppProperties appProperties;

    @Override
    public void run(String... args) throws Exception {

        logger.info("Colour: {}", appProperties.getColour());
        logger.info("Language: {}", appProperties.getLang());
        logger.info("Theme: {}", appProperties.getTheme());
    }
}

```

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

`com/zetcode/Application.java`

```java
package com.zetcode;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application  {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

```

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

## Spring Boot `@ConfigurationProperties`示例 II

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

```java
pom.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           │   Application.java
│   │           │   MyRunner.java
│   │           └───config
│   │                   MailProperties.java
│   └───resources
│           application.properties
│           mail.properties
└───test
    └───java

```

这是项目结构。

`pom.xml`

```java
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zetcode</groupId>
    <artifactId>springbootconfigurationpropertiesvalidation</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

```

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

`resources/application.properties`

```java
spring.main.banner-mode=off

```

这是`application.properties`文件。

`resources/mail.properties`

```java
hostname=info@example.com
port=9000
from=admin@example.com

recipients[0]=user1@example.com
recipients[1]=user2@example.com
recipients[2]=user3@example.com
recipients[3]=user4@example.com

```

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

`com/zetcode/config/MailProperties.java`

```java
package com.zetcode.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;

@Configuration
@PropertySource("classpath:mail.properties")
@ConfigurationProperties
@Validated
public class MailProperties {

    @NotNull
    private String hostname;

    @Min(1000)
    @Max(10000)
    private int port;

    @NotNull
    private String from;

    @NotNull
    private List<String> recipients;

    public String getHostname() {
        return hostname;
    }

    public void setHostname(String hostname) {
        this.hostname = hostname;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public List<String> getRecipients() {
        return recipients;
    }

    public void setRecipients(List<String> recipients) {
        this.recipients = recipients;
    }
}

```

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

`com/zetcode/MyRunner.java`

```java
package com.zetcode;

import com.zetcode.config.MailProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyRunner implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    @Autowired
    private MailProperties mailProperties;

    @Override
    public void run(String... args) throws Exception {

        logger.info("Hostname: {}", mailProperties.getHostname());
        logger.info("Port: {}", mailProperties.getPort());
        logger.info("From: {}", mailProperties.getFrom());
        logger.info("Recipients: {}", mailProperties.getRecipients());
    }
}

```

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

`com/zetcode/Application.java`

```java
package com.zetcode;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

```

这是`Application`类。

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

在本教程中，我们展示了如何使用`@ConfigurationProperties`从外部文件读取配置属性。 您可能也对相关教程感兴趣： [Spring `PropertySource`教程](/spring/propertysource/)， [Spring Boot `CommandLineRunner`教程](/springboot/commandlinerunner/)， [Java 教程](/lang/java/)或列出[所有 Spring Boot 教程](/all/#springboot)。