外部配置和绑定到 Java 对象的所有注解详细使用方式

加粗样式加粗样式用于处理外部配置和绑定到 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则适合于单一配置项的情况。**
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值