如何让@EnableConfigurationProperties的值注入到@Value中

 更新时间:2025年06月07日 10:15:28   作者:Boom_Man  
这篇文章主要介绍了如何让@EnableConfigurationProperties的值注入到@Value中的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

需求背景

定义了一个@ConfigurationProperties的配置类,然后在其中定义了一些定时任务的配置,如cron表达式,因为项目会有默认配置,遂配置中有默认值

大体如下:

@Data
@Validated
@ConfigurationProperties(value = "task")
public class TaskConfigProperties {
    /**
     * 任务A在每天的0点5分0秒进行执行
     */
     @NotBlank
    private String taskA = "0 5 0 * * ? ";

}

定时任务配置:

    @Scheduled(cron = "${task.task-a}")
    public void finalCaseReportGenerate(){
        log.info("taskA定时任务开始执行");
        //具体的任务
        log.info("taskA定时任务完成执行");
    }

但是如上直接使用是有问题的${task.taskA}是没有值的,必须要在外部化配置中再写一遍,这样我们相当于默认值就没有用了,这怎么行呢,我们来搞定他。

探究其原理

@ConfigurationProperties@ValueSpringEl 他们之间的关系和区别及我认为的正确使用方式。

首先@ConfigurationProperties 是Spring Boot引入的,遂查询官方文档的讲解

Spring Boot -> Externalized Configuration

我们发现外部化配置中没有值的话,报错是在org.springframework.util.PropertyPlaceholderHelper#parseStringValue

其中org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver是解析的关键

我们只要把默认值装载到系统中,让org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver#resolvePlaceholder可以解析到就可以了

遂我们可以把值装载到Environment中

/**
 * @author wangqimeng
 * @date 2020/3/4 0:04
 */
@Data
@Slf4j
@Validated
@ConfigurationProperties(prefix = "task")
public class TaskConfigProperties implements InitializingBean , EnvironmentPostProcessor {

    /**
     * 任务A在每天的0点5分0秒进行执行
     */
    @NotBlank
    private String taskA = "0 5 0 * * ? ";

    @Value("${task.task-a}")
    public String taskAValue;

    @Autowired
    private Environment environment;

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("taskAValue:{}",taskAValue);
    }

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        log.info("TaskConfigProperties-> postProcessEnvironment 开始执行");
        //取到当前配置类上的信息
        MutablePropertySources propertySources = environment.getPropertySources();
        Properties properties = new Properties();
        if (taskA != null) {
            properties.put("task.task-a", this.taskA);
        }
        PropertySource propertySource = new PropertiesPropertySource("task", properties);
        //即优先级低
        propertySources.addLast(propertySource);
    }
}

需要在META-INF -> spring.factories中配置

org.springframework.boot.env.EnvironmentPostProcessor=\
cn.boommanpro.config.TaskConfigProperties

所以addLast是优先级最低的,让我们新加入的配置优先级最低。

以上就简单的完成了我们的需求。

最终实现

配置类中的有默认值的不需要在External Configuration中再度配置

通过一个注解@EnableBindEnvironmentProperties,绑定含有@ConfigurationPropertiesClass的默认值到Environment

  • @EnableBindEnvironmentProperties
/**
 * @author wangqimeng
 * @date 2020/3/4 1:21
 */
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EnableBindEnvironmentProperties {


    Class<?>[] value() default {};
}
  • @EnableBindEnvironmentPropertiesRegister
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;

/**
 * @author wangqimeng
 * @date 2020/3/4 15:11
 */
@Slf4j
public class EnableBindEnvironmentPropertiesRegister implements EnvironmentPostProcessor {

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        MutablePropertySources propertySources = environment.getPropertySources();
        EnableBindEnvironmentProperties annotation = application.getMainApplicationClass().getAnnotation(EnableBindEnvironmentProperties.class);
        Arrays.stream(annotation.value())
                .forEach(aClass -> registerToEnvironment(propertySources, aClass));
    }

    public void registerToEnvironment(MutablePropertySources propertySources, Class<?> clazz) {
        ConfigurationProperties annotation = clazz.getAnnotation(ConfigurationProperties.class);
        if (annotation == null) {
            return;
        }
        String prefix = annotation.prefix();
        String name = String.format("%s-%s", prefix, clazz.getName());
        try {
            Properties properties = toProperties(prefix, clazz.newInstance());
            PropertySource propertySource = new PropertiesPropertySource(name, properties);
            propertySources.addLast(propertySource);
        } catch (Exception e) {
            log.error("Exception:", e);
            throw new RuntimeException();
        }

    }

    public Properties toProperties(String prefix, Object o) throws Exception {
        Properties properties = new Properties();
        Map<String, Object> map = objectToMap(o);
        map.forEach((s, o1) -> {
            properties.put(String.format("%s.%s", prefix, camelToUnderline(s)), o1);
        });

        return properties;
    }

    public static String camelToUnderline(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append("-");
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>(10);
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (key.compareToIgnoreCase("class") == 0) {
                continue;
            }
            Method getter = property.getReadMethod();
            Object value = getter != null ? getter.invoke(obj) : null;
            if (value == null) {
                continue;
            }
            map.put(key, value);
        }

        return map;
    }
}

配置到META-INF/spring.factories

# Application Listeners
org.springframework.boot.env.EnvironmentPostProcessor=\
cn.boommanpro.annotation.EnableBindEnvironmentPropertiesRegister

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 快速搭建springboot项目(新手入门)

    快速搭建springboot项目(新手入门)

    本文主要介绍了快速搭建springboot项目(新手入门),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-07-07
  • 美化java代码,从合理注释开始

    美化java代码,从合理注释开始

    在Java的编写过程中我们需要对一些程序进行注释,除了自己方便阅读,更为别人更好理解自己的程序,可以是编程思路或者是程序的作用,总而言之就是方便自己他人更好的阅读。下面我们来一起学习一下吧
    2019-06-06
  • 使用Java反射机制提高SpringBoot的代码质量和可维护性

    使用Java反射机制提高SpringBoot的代码质量和可维护性

    保持好的代码质量和遵守编码标准是开发可维护和健壮软件的重要方面,在本文中,我们将探讨如何使用 Java 反射来提高 Spring Boot 应用程序的代码质量和可维护性,需要的朋友可以参考下
    2023-10-10
  • Java实现SM3withSM2签名和验证的基本示例

    Java实现SM3withSM2签名和验证的基本示例

    这篇文章主要介绍了Java实现SM3withSM2签名和验证的基本示例,SM3withSM2是一种在Java中使用的密码学算法组合,结合了椭圆曲线公钥密码算法SM2和密码哈希算法SM3,它主要用于数字签名和数据完整性校验,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2025-04-04
  • 浅析对Java关键字final和static的理解

    浅析对Java关键字final和static的理解

    本文主要给大家谈谈小编对java关键字final和static的理解,本文给大家介绍的较详细,需要的朋友参考参考下
    2017-04-04
  • 深入讲解Java的对象头与对象组成

    深入讲解Java的对象头与对象组成

    由于Java面向对象的思想,在JVM中需要大量存储对象,存储时为了实现一些额外的功能,需要在对象中添加一些标记字段用于增强对象功能,这些标记字段组成了对象头,下面这篇文章主要给大家介绍了关于Java对象头与对象组成的相关资料,需要的朋友可以参考下
    2022-02-02
  • Java如何取掉json数据中值为null的属性字段

    Java如何取掉json数据中值为null的属性字段

    这篇文章主要介绍了Java如何取掉json数据中值为null的属性字段,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03
  • MyBatis处理CLOB/BLOB类型数据以及解决读取问题

    MyBatis处理CLOB/BLOB类型数据以及解决读取问题

    这篇文章主要介绍了MyBatis处理CLOB/BLOB类型数据以及解决读取问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-04-04
  • SpringCloudAlibaba分布式组件详解

    SpringCloudAlibaba分布式组件详解

    这篇文章主要介绍了简单了解Spring Cloud Alibaba分布式组件相关知识,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2021-08-08
  • Java Lambda表达式和函数式接口实例分析

    Java Lambda表达式和函数式接口实例分析

    这篇文章主要介绍了Java Lambda表达式和函数式接口,结合实例形式分析了Java8 Lambda表达式和函数式接口相关原理、用法及操作注意事项,需要的朋友可以参考下
    2019-09-09

最新评论