web加载properties的方式

原网址:https://www.cnblogs.com/hafiz/p/5876243.html

1. 用配置文件加载,用注解@Value绑定值

  • 通过context:property-placeholder加载配置文件jdbc.properties中的内容
<context:property-placeholder location="classpath:properties/application.properties" ignore-unresolvable="true" />
  • 使用注解的方式注入,主要用在java代码中使用注解注入properties文件中相应的value值
<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
   <!-- 这里是PropertiesFactoryBean类,它也有个locations属性,也是接收一个数组,跟上面一样 -->
   <property name="locations">
       <array>
          <value>classpath:application.properties</value>
       </array>
   </property>
</bean>
  • 使用util:properties标签进行暴露properties文件中的内容
<util:properties id="propertiesReader" location="classpath:jdbc.properties"/>

使用如上配置需要加入下面配置

<beans xmlns:util="http://www.springframework.org/schema/util"
       http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util.xsd">

如上三种配置都可以用注解方式获取properties文件中的属性

@Value("${sub.thread.num}")
private int num;

2. 通过PropertyPlaceholderConfigurer在加载上下文的时候暴露properties到自定义子类的属性中以供程序中使用

<bean id="propertyConfigurer" class="com.hafiz.www.util.PropertyConfigurer">
   <property name="ignoreUnresolvablePlaceholders" value="true"/>
   <property name="ignoreResourceNotFound" value="true"/>
   <property name="locations">
       <list>
          <value>classpath:jdbc.properties</value>
       </list>
   </property>
</bean>

自定义PropertiesConfigurer 类

public class PropertiesConfigurer extends PropertyPlaceholderConfigurer {

    private Properties props;       // 存取properties配置文件key-value结果

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
                            throws BeansException {
        super.processProperties(beanFactoryToProcess, props);
        this.props = props;
    }

    public String getProperty(String key){
        return this.props.getProperty(key);
    }

    public String getProperty(String key, String defaultValue) {
        return this.props.getProperty(key, defaultValue);
    }

    public Object setProperty(String key, String value) {
        return this.props.setProperty(key, value);
    }
}

3. 自定义工具类PropertiesUtils,并在该类的static静态代码块中读取properties文件内容保存在static属性中以供别的程序使用

  • 自定义propertiesUtils类,使用inputStream读取文件,获取properties文件中的内容
package com.silencer.web.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * @description 自定义获取properties工具类.
 * @author Silencer
 * @date 2018-08-27 13:29:49
 * @version v_1.0
 */
public class PropertiesUtils {

	private static Logger log = LoggerFactory.getLogger(PropertiesUtils.class);

	private static Properties props;

	static {
		init();
	}

	/**
	 * TODO 默认加载配置文件
	 */
	private synchronized static void init() {
		InputStream input = null;
		try {
			props = new Properties();
			input = PropertiesUtils.class.getClassLoader().getResourceAsStream("application.properties");
			props.load(input);
		} catch (FileNotFoundException e) {
			log.error("---------> 未找到properties文件!", e);
		} catch (IOException e) {
			log.error("---------> 加载properties文件出错!", e);
		} finally {
			try {
				if (null != input) {
					input.close();
				}
			} catch (IOException e) {
				log.error("properties文件流关闭出现异常", e);
			}
		}
	}

	/**
	 * TODO 通过属性名获取属性值.
	 * 
	 * @param key
	 * @return
	 */
	public static String getProperty(String key) {
		if (!StringUtils.isEmpty(key)) {
			String value = props.getProperty(key.trim());
			if (!StringUtils.isEmpty(value)) {
				return value.trim();
			}
		}
		return null;
	}

	/**
	 * TODO 通过属性名获取属性值,当属性值为空时,取默认属性值.
	 * 
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static String getProperty(String key, String defaultValue) {
		String value = getProperty(key);
		if (!StringUtils.isEmpty(value)) {
			return value.trim();
		} else {
			return defaultValue;
		}
	}

}
  • 创建propertiesBundle文件,使用java.util.ResourceBundle来获取properties中的属性
package com.silencer.web.utils.properties;

import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * @description 自定义获取properties工具类.
 * @author Silencer
 * @date 2018-08-27 13:29:49
 * @version v_1.0
 */
public class PropertiesBundle {

	private static Logger log = LoggerFactory.getLogger(PropertiesBundle.class);

	private static ResourceBundle resource;

	static {
		init();
	}

	/**
	 * TODO 默认加载配置文件
	 */
	private synchronized static void init() {
		// 首先在classpath下面的properties文件夹中找application_zh_CN.properties文件;
                // 然后找application_zh.properties文件;
		// 然后找application.properties文件
		resource = ResourceBundle.getBundle("properties/application", new Locale("zh", "CN"));
	}

	/**
	 * TODO 通过属性名获取属性值.
	 * 
	 * @param key
	 * @return
	 */
	public static String getProperty(String key) {
		if (!StringUtils.isEmpty(key)) {
			// 此处区分大小写
			String value = resource.getString(key.trim());
			if (!StringUtils.isEmpty(value)) {
				log.info("---------> {} <---------", value.trim());
				return value.trim();
			}
		}
		return null;
	}

	/**
	 * TODO 通过属性名获取属性值,当属性值为空时,取默认属性值.
	 * 
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static String getProperty(String key, String defaultValue) {
		String value = getProperty(key);
		if (!StringUtils.isEmpty(value)) {
			return value.trim();
		} else {
			return defaultValue;
		}
	}

}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值