一、使用 @Value 注解:
@Value
注解允许您将属性值直接注入到Spring Bean中。您可以在字段或方法参数上使用该注解,以获取配置文件中的值。
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
@Value("${my.property}")
private String myProperty;
// Getter and setter for myProperty
}
在上述示例中,${my.property}
是配置文件中的属性键。通过将 @Value
注解应用到字段 myProperty
上,Spring会将配置文件中的属性值注入到该字段。
优点:
1、简单直接,适用于注入单个属性值。
2、可以直接用于字段,无需定义额外的类。
缺点:
1、不适用于复杂的属性映射。
2、不支持默认值,属性不存在时会抛出异常。
二、使用 @ConfigurationProperties 注解:
@ConfigurationProperties
注解允许您将一组相关的属性映射到一个POJO(普通Java对象)中。通过在应用程序配置类上使用此注解,可以将配置文件中的属性映射到该类的属性中。
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "my")
public class MyProperties {
private String property;
// Getter and setter for property
}
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "my")
public class MyProperties {
private String property;
// Getter and setter for property
}
在上述示例中,prefix = "my"
表示将具有前缀 my
的配置属性映射到 MyProperties
类中的属性。
优点:
- 支持复杂的属性映射。
- 可以提供默认值,属性不存在时使用默认值。
缺点:
- 需要定义一个POJO类来映射属性。
三、使用 Environment 对象:
Spring Boot的 Environment
对象提供了一种检索配置属性的方式。您可以在任何Spring Bean中注入 Environment
对象,并使用其方法来获取配置属性的值。
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
@Component
public class MyComponent {
@Autowired
private Environment environment;
public String getProperty(String key) {
return environment.getProperty(key);
}
}
在上述示例中,通过注入 Environment
对象,您可以使用 getProperty
方法来获取配置属性的值。
优点:
- 灵活,可以在任何地方使用。
- 可以处理复杂的属性层次结构。
缺点:
- 需要手动处理属性值的类型转换。