Spring注解-@ConfigurationProperties

本文详细介绍了SpringBoot中的@ConfigurationProperties注解,如何将外部配置文件中的属性自动绑定到Java对象,以及如何通过prefix指定配置前缀,以CaptchaProperties类为例进行说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、@ConfigurationProperties作用是什么?

@ConfigurationProperties 是 Spring Boot 中的一个注解,用于将外部配置(通常是从 application.propertiesapplication.yml 文件中读取的配置)绑定到一个 Java 对象上。

二、@ConfigurationProperties举例说明

2.1例如,@ConfigurationProperties(prefix = "com.captcha")

让我们来解释一下:

  • @ConfigurationProperties:这个注解表示一个类可以用于绑定配置属性。它告诉 Spring Boot 将被注解类的字段与配置文件中具有相匹配名称的属性绑定在一起。

  • prefix = "com.captcha":这个参数指定了在配置文件中用来识别要绑定到被注解类的字段的属性的前缀。在这个例子中,以 com.captcha 开头的属性在 application.propertiesapplication.yml 中将会被绑定到该类的字段上。

例如,如果你的配置文件中有像 com.captcha.enabledcom.captcha.lengthcom.captcha.timeout 等属性,Spring Boot 将会把这些属性绑定到被注解类的字段上。

2.2application.yaml配置

com:
  captcha:
    enabled: true
    timeout: 5m
    length: 160

2.3 属性绑定类

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

@Component
@ConfigurationProperties(prefix = "com.captcha")
public class CaptchaProperties {
    private boolean enabled;
    private int length;
    private int timeout;

    // Getters and setters for the properties
    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }
}

2.4使用配置类方式

@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Resource
    private CaptchaProperties captchaProperties;

        
    @Override
    public CaptchaImageRespVO getCaptchaImage() {
        captchaProperties.getEnabled();
         captchaProperties.getLength();
        captchaProperties.getTimeout();
    }

}

三、总结

如何不同过写set方法,直接通过配置和注解的方式来讲配置中的参数注入到类中,并可以在类中直接使用?可以通过@ConfigurationProperties(prefix = "com.captcha") 注解,将此注解加载类上。然后在其它地方注入并获取想要的属性即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值