Spring Boot之@ConfigurationProperties注解

博客介绍了在Spring Boot中,使用@ConfigurationProperties注解可读取配置文件同类信息并封装成对象,与@Bean注解同时使用时实体可不加该注解。还说明了成功注入需满足的条件,如配置key与属性名对应且有公共set方法等,并给出示例代码。

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

  在实体上使用@ConfigurationProperties注解,可以读取配置文件中同类配置信息并封装成对象。和@Bean注解同时使用时可以不用在实体上使用该注解。

满足以下三条可以成功注入:

  • 1.配置key(除前缀外)与属性名相同且属性有公共set方法可注入。
  • 2.以‘-’连接的配置key(除前缀外)自动处理成驼峰格式与属性名相同且属性有公共set方法可注入。
  • 3.父类属性拥有公共set方法的,符合上述两条可注入。

示例代码:

	public class Parent {
	
		private String userType;

		public String getUserType() {
			return userType;
		}

		public void setUserType(String userType) {
			this.userType = userType;
		}

		@Override
		public String toString() {
			return "Parent [userType=" + userType + "]";
		}
	}
	@ConfigurationProperties(prefix = "test")
	public class Son extends Parent {
		
		private String userName;
		
		private Integer age;

		public String getUserName() {
			return userName;
		}

		public void setUserName(String userName) {
			this.userName = userName;
		}

		public Integer getAge() {
			return age;
		}

		public void setAge(Integer age) {
			this.age = age;
		}

		@Override
		public String toString() {
			return "Son [userName=" + userName + ", age=" + age + ", toString()=" + super.toString() + "]";
		}
	}

配置文件中相关配置:

test.user-name=Qiwan
test.age=18
test.user-type=human

执行单元测试:

	@Autowired
	private Son son;
	
	@Test
	public void test1(){
		log.info("SON:{}", son);
	}

输出结果: SON:Son [userName=Qiwan, age=18, toString()=Parent [userType=human]]

和@Bean注解同时使用时:

去掉Son类上的@ConfigurationProperties(prefix = “test”)注解,增加SonConfig类。

	@Configuration
	public class SonConfig {
		
		@Bean
		@ConfigurationProperties(prefix = "test")
		public Son getSon(){
			return new Son();
		}
	}

执行上述相同单元测试代码,结果同上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值