栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

@ConfigurationProperties注解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

@ConfigurationProperties注解

@ConfigurationProperties注解

@ConfigurationProperties是springboot提供读取配置文件的一个注解。其对应的bean的后置处理器为**ConfigurationPropertiesBindingPostProcessor**

Spring源码中大量使用了ConfigurationProperties注解,比如server.port就是由该注解获取到的,通过与其他注解配合使用,能够实现Bean的按需配置。

该注解有一个**prefix**属性,通过指定的前缀,绑定配置文件中的配置,该注解可以放在类上,也可以放在方法上。

@ConfigurationProperties注解源码:

  // IntelliJ API Decompiler stub source generated from a class file
  // Implementation of methods is not available

package org.springframework.boot.context.properties;

@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.METHOD})
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.documented
public @interface ConfigurationProperties {
    @org.springframework.core.annotation.AliasFor("prefix")
    java.lang.String value() default "";

    @org.springframework.core.annotation.AliasFor("value")
    java.lang.String prefix() default "";

    boolean ignoreInvalidFields() default false;

    boolean ignoreUnknownFields() default true;
}

在SpringBoot中,当需要获取到配置文件数据时,除了可以用Spring自带的@Value注解外,SpringBoot提供了一种更加方便的方式:@ConfigurationProperties。只要在bean上添加上这个注解,指定好配置文件的前缀,那么对应的配置文件数据就会自动填充到bean中。

举个栗子,现在有如下配置:

myconfig.name=test
myconfig.age=22
myconfig.desc=这是我的测试描述

添加对应的配置类,并添加上注解@ConfigurationProperties,指定前缀为myconfig:

@Component
@ConfigurationProperties(prefix = "myconfig")
public class MyConfig {
private String name;
private Integer age;
private String desc;
  //get/set 略
  @Override
public String toString() {
	return "MyConfig [name=" + name + ", age=" + age + ", desc=" + desc + "]";
}
}

添加使用:

public static void main(String[] args) throws Exception {
	SpringApplication springApplication = new SpringApplication(Application.class);
	// 非web环境
	springApplication.setWebEnvironment(false);
	ConfigurableApplicationContext application = springApplication.run(args);

	MyConfig config = application.getBean(MyConfig.class);
	log.info(config.toString());
	application.close();
}

可以看到输出log:

com.cml.chat.lesson.lesson3.Application - MyConfig [name=test, age=22, desc=这是我的测试描述]
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/667071.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号