当前位置:   article > 正文

Spring Boot之@ConfigurationProperties注解_@configurationproperties会自动映射驼峰吗

@configurationproperties会自动映射驼峰吗

  在实体上使用@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 + "]";
		}
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
	@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() + "]";
		}
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

配置文件中相关配置:

test.user-name=Qiwan
test.age=18
test.user-type=human
  • 1
  • 2
  • 3

执行单元测试:

	@Autowired
	private Son son;
	
	@Test
	public void test1(){
		log.info("SON:{}", son);
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

输出结果: 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();
		}
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号