springboot 手动获取spring yaml配置值(手动实现@value)

发布于:2024-06-22 ⋅ 阅读:(136) ⋅ 点赞:(0)
package com.kittlen.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component;
import org.springframework.util.PropertyPlaceholderHelper;
import org.springframework.util.SystemPropertyUtils;


/**
 * @author kittlen
 * @date 2024-06-18 17:54
 * @description
 */

@Component
public class ManualValueUtil {
    @Autowired
    private Environment environment;

    private String placeholderPrefix = SystemPropertyUtils.PLACEHOLDER_PREFIX;

    private String placeholderSuffix = SystemPropertyUtils.PLACEHOLDER_SUFFIX;

    private String valueSeparator = SystemPropertyUtils.VALUE_SEPARATOR;

    PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper(this.placeholderPrefix, this.placeholderSuffix,
            this.valueSeparator, true);

    public String getValue(String key){
        return propertyPlaceholderHelper.replacePlaceholders(key, environment::getProperty);
    }
}

使用

    @Autowired
    ManualValueUtil manualValueUtil;
	
	 //String value = manualValueUtil.getValue("value");

	//例如	
	 String value = manualValueUtil.getValue("${spring.application.name}");


网站公告

今日签到

点亮在社区的每一天
去签到