加粗样式加粗样式用于处理外部配置和绑定到 Java 对象的所有注解
在Java中,用于处理外部配置并将其绑定到Java对象的常见注解主要有@Value和@ConfigurationProperties。
1、@Value
@Value注解可以将外部配置(如环境变量、系统属性、应用配置文件等)绑定到Java对象的字段上。
1.1 代码内容如下:
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
}
@ConfigurationProperties
1.2 在配置文件(如application.properties)中,内容如下:
<--对应的配置文件内容如下:->
my:
property: test
2、@ConfigurationProperties
@ConfigurationProperties注解可以将配置文件中的一组属性绑定到Java对象上,这在配置较为复杂的属性时尤其有用。
2.1 代码内容如下:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "student")
public class Student {
private String testName;
private Interge testAge;
// Getter and Setter
}
2.2 在配置文件(如application.properties)中,内容如下:
<--对应的配置文件内容如下:->
studenet:
test_name: test
test_age: 3
3、@NestedConfigurationProperty
这个注解通常与 @ConfigurationProperties 一起使用,用于支持将嵌套的配置属性绑定到一个嵌套的 Java 对象中
3.1 代码内容如下:
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
@Data
@Configuration
@ConfigurationProperties(prefix = “student”)
public class Student {
private String testName;
private Interge testAge;
/**
* 老师信息
*/
@NestedConfigurationProperty
private List<Teacher> teacherinfos = new ArrayList<>();
}
################################################################
//老师类
@Data
public class Student {
private String testTeacherName;
private Interge testTeacherAge;
}
3.2 在配置文件(如application.properties)中,内容如下:
<--对应的配置文件内容如下:->
studenet:
test-name: test
test-age: 3
teacherinfos:
#多个老师配置信息
-test-teacher-name:test1
test-teacher-age:4
-test-teacher-name:test2
test-teacher-age:5
-test-teacher-name:test3
test-teacher-age:6
4、总结:
以上三种注解都可以用来处理外部配置:
- @ConfigurationProperties 适合 有嵌套的对象(配置项较多)
- @ConfigurationProperties更适合于无嵌套对象(配置项较多),
- @Value则适合于单一配置项的情况。**

1065

被折叠的 条评论
为什么被折叠?



