一、@ConfigurationProperties作用是什么?
@ConfigurationProperties
是 Spring Boot 中的一个注解,用于将外部配置(通常是从 application.properties
或 application.yml
文件中读取的配置)绑定到一个 Java 对象上。
二、@ConfigurationProperties举例说明
2.1例如,@ConfigurationProperties(prefix = "com.captcha")
,
让我们来解释一下:
-
@ConfigurationProperties
:这个注解表示一个类可以用于绑定配置属性。它告诉 Spring Boot 将被注解类的字段与配置文件中具有相匹配名称的属性绑定在一起。 -
prefix = "com.captcha"
:这个参数指定了在配置文件中用来识别要绑定到被注解类的字段的属性的前缀。在这个例子中,以com.captcha
开头的属性在application.properties
或application.yml
中将会被绑定到该类的字段上。
例如,如果你的配置文件中有像 com.captcha.enabled
、com.captcha.length
、com.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") 注解,将此注解加载类上。然后在其它地方注入并获取想要的属性即可。