无名阁,只为技术而生。流水不争先,争的是滔滔不绝。

(configurationproperties注解在方法上) Spring中的@ConfigurationProperties在方法上的使用详解 Spring Boot 的 @ConfigurationProperties 特性概述 全网首发(图文详解1)

前沿技术 Micheal 3个月前 (06-22) 43次浏览 已收录 扫描二维码

(configurationproperties注解在方法上) Spring中的@ConfigurationProperties在方法上的使用详解

@ConfigurationPropertiesSpring Boot 的一个特性,允许你把配置文件(比如 application.properties 或 application.yml)中的属性绑定到一个 Java 对象上。这样做的好处是你可以以类型安全的方式访问这些属性。

在方法上使用 @ConfigurationProperties 较为少见,这个注解通常用来标注类或者 @Bean 方法,以表明该类或者创建的 Bean 将会与配置文件中的指定属性进行绑定。

下面我将介绍如何在类级别上使用 @ConfigurationProperties,因为这是它的典型用途。

步骤 1: 创建一个配置属性类

首先,你需要创建一个包含配置属性的类,并在类上使用 @ConfigurationProperties 注解。假定我们有以下的配置属性:

app:
  email:
    host: smtp.example.com
    port: 587
    username: user@example.com
    password: secret

相应的配置属性类可能如下所示:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix="app.email")
public class EmailProperties {

    private String host;
    private int port;
    private String username;
    private String password;

    // standard getters and setters
}

注意,这里我们使用了 prefix 属性指定了配置文件中的哪一部分属性将与这个类中的字段绑定。

步骤 2: 使用 @EnableConfigurationProperties

在你的配置类(通常带有 @Configuration 注解的类)中启用 @ConfigurationProperties 处理,通过添加 @EnableConfigurationProperties 注解:

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

@Configuration
@EnableConfigurationProperties(EmailProperties.class)
public class AppConfig {
    // ...
}

步骤 3: 注入使用配置属性

现在,你可以在需要使用这些配置属性的地方注入 EmailProperties 类的实例:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EmailService {

    private final EmailProperties emailProperties;

    @Autowired
    public EmailService(EmailProperties emailProperties) {
        this.emailProperties = emailProperties;
    }

    // Now you can use emailProperties.getHost(), emailProperties.getPort(), etc.
}

经过这些设置后,Spring Boot 将会自动把配置文件中的属性值绑定到 EmailProperties 类的字段上。

注意: 从 Spring Boot 2.2.0 版本开始,如果在配置类中使用 @ConfigurationProperties 注解,不再需要显式地添加 @EnableConfigurationProperties,但在其他非配置的类上任然需要添加。

理解和实现以上步骤后,你的应用程序应该能够利用 @ConfigurationProperties 功能,将配置信息以类型安全的方式注入到 Spring Boot 应用程序中。这种做法的代码更加清晰,错误风险较低,并且配置更加容易管理和维护。
(fmt.println) Go语言中println和fmt.Println区别 Go语言中的println和fmt.Println差异 全网首发(图文详解1)
(js模拟点击) javascript模拟鼠标点击事件原理和实现方法 事件模拟原理 全网首发(图文详解1)

喜欢 (0)
[]
分享 (0)
关于作者:
流水不争先,争的是滔滔不绝