Spring下,业务代码直接获取properties文件属性值

在spring通过 @Value(“${key}”) 注解方式获取属性文件有点麻烦,如果有个值要获取就要写多个成员属性,麻烦。
这里继承org.springframework.beans.factory.config.PropertyPlaceholderConfigurer,编写获取、设置属性值方法,封装作为工具类,在业务代码直接拿到properties文件属性值

继承PropertyPlaceholderConfigurer

继续PropertyPlaceholderConfigurer,编写工具类Configuration 。

import java.io.IOException;
import java.util.Properties;
import java.util.regex.Matcher;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

public class Configuration extends PropertyPlaceholderConfigurer {

    private static final Logger log = LogManager.getLogger(Configuration.class);

    private Properties properties;
    private final static String ERR_MSG = "从配置文件中不能取得传入参数的返回值:";

    /**
     * Use singleton pattern, only return one instance of Configuration.
     * 
     * @return Configuration
     */
    public static Configuration getInstance() {
        //这里是静态方法,获取Spring中configuration bean,就是当前类bean。注意这块代码逻辑。或者直接去掉,通过依赖注入使用该bean。
        return (Configuration) SpringUtil.getBean("configuration");
    }

    /**
     * Retun a value for certain key.
     * 
     * @param key
     *            a certain key define in properties file.
     * @return value
     */
    public String getValue(String key) {
        if (null == properties) {
            try {
                properties = mergeProperties();
            } catch (IOException e) {
                log.error(ERR_MSG + ":" + key);
                log.error(e);
            }
        }
        String value = properties.getProperty(key);
        if (value == null) {
            log.debug(ERR_MSG + ":" + key);
        }

        return processExpValue(value);
    }


    public void setValue(String key, String value){
        if (null != properties) {
            properties.put(key, value);
        }
    }

    /**
     * 获取属性值(属性值中带${}则相应的取值替换)
     * add by duanbo 20140903
     * 
     * @param key 属性KEY
     * @return 属性值
     */
    public String getExpValue(String key)
    {
        String val = getValue(key);
        return processExpValue(val);
    }

    /**
     * 处理表达式值
     * 
     * @param value 属性值(包含${}表达式)
     * @return
     */
    public String processExpValue(String value)
    {
        String regx = ".*\\$\\{.*\\}.*";
        String val = value;

        // 如果属性值不为空并且属性值中有${}表达式
        if(StringUtils.isNotBlank(val) && val.matches(regx))
        {
            // 处理属性值中的${}表达式
            for(String str = val; str.matches(regx);)
            {
                // key开始索引
                int startIndex = str.indexOf("${") + 2;
                // key结束索引
                int endIndex = str.indexOf("}");

                // 当前属性key
                String keyX = str.substring(startIndex, endIndex);
                // 当前属性表达式
                String exp = "\\$\\{" + keyX + "\\}";

                // 当前属性值
                String valX = getValue(keyX);
                String valY = valX;
                if(null != valY)
                {
                    if(valY.matches(regx))
                    {
                        valY = processExpValue(valY);
                    }

                    if(null != valY)
                    {
                        if(valY.matches(regx) && StringUtils.equals(valX, valY))
                        {
                            log.warn(valY + " 中表达式处理失败!");
                        }
                        else
                        {
                            val = val.replaceAll(exp, Matcher.quoteReplacement(valY));
                        }
                    }
                }

                // 每处理掉一个就将替换掉一个,直到无
                str = str.replaceAll(exp, (null == valY || valY.matches(regx)) ? "" : Matcher.quoteReplacement(valY));
            }
        }

        return val;
    }

}

配置spring bean,载入属性文件

在spring中配置属性文件bean,载入属性文件。可以放在不改动的地方,根据需要,依不同环境载入不同的属性文件。

<!-- 属性文件读入 -->
    <bean id="configuration" class="com.util.Configuration">
        <property name="locations">
            <list>
                <!-- 开发应用配置 -->

                <value>classpath*:config/config-dev.properties</value>
                <!--测试应用配置
                     <value>classpath*:config/config-test.properties</value> -->

                <!--正式应用配置
                    <value>classpath*:config/config-product.properties</value>
                 -->
            </list>
        </property>
    </bean>

使用

Properties配置文件

solrServerUrl=http://ip:port

应用获取

@Component
public class Test {
    @Autowired
    private Configuration configuration;


    public void as() {
        //方法一,依赖注入获取配置文件bean
        String solrServerUrl1=configuration.getValue("solrServerUrl");

        //方法二,通过Configuration类中写好的静态获取spring上下文中的configuration bean,获取属性值。
        String solrServerUrl2=Configuration.getInstance().getValue("solrServerUrl");
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring框架提供了一种便捷的方式来读取properties文件中的配置信息。在Spring中,我们可以使用PropertyPlaceholderConfigurer或PropertySourcesPlaceholderConfigurer来加载properties文件。 PropertyPlaceholderConfigurer是在Spring 3.1之前版本中使用的类,用于从classpath或指定位置加载properties文件。它可以将properties文件中的键对替换为Spring配置文件中的占位符。通过将PropertyPlaceholderConfigurer配置为Bean的一部分,我们可以在XML配置文件中使用占位符来引用properties文件中的。例如,我们可以在XML中配置一个DataSource Bean,并通过占位符引用properties文件中的数据库连接信息。 PropertySourcesPlaceholderConfigurer是从Spring 3.1版本引入的新类,它可以更方便地处理properties文件。与PropertyPlaceholderConfigurer不同,PropertySourcesPlaceholderConfigurer允许我们使用@Value注解来直接注入properties文件中的属性。我们可以在Java配置类或XML配置文件中配置PropertySourcesPlaceholderConfigurer,并在需要的地方使用@Value注解来获取properties文件中的属性。 无论我们使用哪种方式来读取properties文件,我们都需要确保将其配置为Spring容器的一部分,并以适当的方式加载它。通常,我们会在Spring配置文件中添加一个bean来加载properties文件,并将其配置为其他bean的属性或参数的。 总结起来,Spring提供了两种主要的方法来读取properties文件:使用PropertyPlaceholderConfigurer或PropertySourcesPlaceholderConfigurer。这些类可以让我们轻松地将properties文件中的配置引入到Spring容器中,并在我们的应用程序中使用它们。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值