跳转至

Spring Boot @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 配置文件。

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

这是项目结构。

pom.xml

<?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

spring.main.banner-mode=off

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

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

com/zetcode/conf/AppProperties.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;
    }
}

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

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

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

com/zetcode/MyRunner.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

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

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

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

这是项目结构。

pom.xml

<?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

spring.main.banner-mode=off

这是application.properties文件。

resources/mail.properties

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

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

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

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 Boot CommandLineRunner教程Java 教程或列出所有 Spring Boot 教程



回到顶部