示例

<util:properties id="db" location="classpath:db.properties" />

全部属性

功能概述

Loads a Properties instance from the resource location specified by the '

<code>location</code>

' attribute.

属性详解

id

#{A['B']}

A means util:properties id

B means properties key

location

The location of the properties file, as a Spring resource location: a URL, a "classpath:" pseudo URL, or a relative file path. Multiple locations may be specified, separated by commas.

ignore-resource-not-found

Specifies if failure to find the property resource location should be ignored. Default is "false", meaning that if there is no file in the location specified an exception will be raised at runtime.

local-override

Specifies whether local properties override properties from files. Default is "false": properties from files override local defaults. If set to "true", local properties will override defaults from files.

scope

The scope of this collection bean: typically "singleton" (one shared instance, which will be returned by all calls to getBean with the given id), or "prototype" (independent instance resulting from each call to getBean). Default is "singleton". Further scopes, such as "request" or "session", might be supported by extended bean factories (e.g. in a web environment).

value-type

The default Java type for nested values. Must be a fully qualified class name.

源码

org.springframework.beans.factory.config.PropertiesFactoryBean extends PropertiesLoaderSupport

/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.springframework.beans.factory.config; import java.io.IOException;
import java.util.Properties; import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.support.PropertiesLoaderSupport; /**
* Allows for making a properties file from a classpath location available
* as Properties instance in a bean factory. Can be used to populate
* any bean property of type Properties via a bean reference.
*
* <p>Supports loading from a properties file and/or setting local properties
* on this FactoryBean. The created Properties instance will be merged from
* loaded and local values. If neither a location nor local properties are set,
* an exception will be thrown on initialization.
*
* <p>Can create a singleton or a new object on each request.
* Default is a singleton.
*
* @author Juergen Hoeller
* @see #setLocation
* @see #setProperties
* @see #setLocalOverride
* @see java.util.Properties
*/
public class PropertiesFactoryBean extends PropertiesLoaderSupport
implements FactoryBean<Properties>, InitializingBean { private boolean singleton = true; private Properties singletonInstance; /**
* Set whether a shared 'singleton' Properties instance should be
* created, or rather a new Properties instance on each request.
* <p>Default is "true" (a shared singleton).
*/
public final void setSingleton(boolean singleton) {
this.singleton = singleton;
} @Override
public final boolean isSingleton() {
return this.singleton;
} @Override
public final void afterPropertiesSet() throws IOException {
if (this.singleton) {
this.singletonInstance = createProperties();
}
} @Override
public final Properties getObject() throws IOException {
if (this.singleton) {
return this.singletonInstance;
}
else {
return createProperties();
}
} @Override
public Class<Properties> getObjectType() {
return Properties.class;
} /**
* Template method that subclasses may override to construct the object
* returned by this factory. The default implementation returns the
* plain merged Properties instance.
* <p>Invoked on initialization of this FactoryBean in case of a
* shared singleton; else, on each {@link #getObject()} call.
* @return the object returned by this factory
* @throws IOException if an exception occured during properties loading
* @see #mergeProperties()
*/
protected Properties createProperties() throws IOException {
return mergeProperties();
} }
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.springframework.core.io.support; import java.io.IOException;
import java.util.Properties; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.springframework.core.io.Resource;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DefaultPropertiesPersister;
import org.springframework.util.PropertiesPersister; /**
* Base class for JavaBean-style components that need to load properties
* from one or more resources. Supports local properties as well, with
* configurable overriding.
*
* @author Juergen Hoeller
* @since 1.2.2
*/
public abstract class PropertiesLoaderSupport { /** Logger available to subclasses */
protected final Log logger = LogFactory.getLog(getClass()); protected Properties[] localProperties; protected boolean localOverride = false; private Resource[] locations; private boolean ignoreResourceNotFound = false; private String fileEncoding; private PropertiesPersister propertiesPersister = new DefaultPropertiesPersister(); /**
* Set local properties, e.g. via the "props" tag in XML bean definitions.
* These can be considered defaults, to be overridden by properties
* loaded from files.
*/
public void setProperties(Properties properties) {
this.localProperties = new Properties[] {properties};
} /**
* Set local properties, e.g. via the "props" tag in XML bean definitions,
* allowing for merging multiple properties sets into one.
*/
public void setPropertiesArray(Properties... propertiesArray) {
this.localProperties = propertiesArray;
} /**
* Set a location of a properties file to be loaded.
* <p>Can point to a classic properties file or to an XML file
* that follows JDK 1.5's properties XML format.
*/
public void setLocation(Resource location) {
this.locations = new Resource[] {location};
} /**
* Set locations of properties files to be loaded.
* <p>Can point to classic properties files or to XML files
* that follow JDK 1.5's properties XML format.
* <p>Note: Properties defined in later files will override
* properties defined earlier files, in case of overlapping keys.
* Hence, make sure that the most specific files are the last
* ones in the given list of locations.
*/
public void setLocations(Resource... locations) {
this.locations = locations;
} /**
* Set whether local properties override properties from files.
* <p>Default is "false": Properties from files override local defaults.
* Can be switched to "true" to let local properties override defaults
* from files.
*/
public void setLocalOverride(boolean localOverride) {
this.localOverride = localOverride;
} /**
* Set if failure to find the property resource should be ignored.
* <p>"true" is appropriate if the properties file is completely optional.
* Default is "false".
*/
public void setIgnoreResourceNotFound(boolean ignoreResourceNotFound) {
this.ignoreResourceNotFound = ignoreResourceNotFound;
} /**
* Set the encoding to use for parsing properties files.
* <p>Default is none, using the {@code java.util.Properties}
* default encoding.
* <p>Only applies to classic properties files, not to XML files.
* @see org.springframework.util.PropertiesPersister#load
*/
public void setFileEncoding(String encoding) {
this.fileEncoding = encoding;
} /**
* Set the PropertiesPersister to use for parsing properties files.
* The default is DefaultPropertiesPersister.
* @see org.springframework.util.DefaultPropertiesPersister
*/
public void setPropertiesPersister(PropertiesPersister propertiesPersister) {
this.propertiesPersister =
(propertiesPersister != null ? propertiesPersister : new DefaultPropertiesPersister());
} /**
* Return a merged Properties instance containing both the
* loaded properties and properties set on this FactoryBean.
*/
protected Properties mergeProperties() throws IOException {
Properties result = new Properties(); if (this.localOverride) {
// Load properties from file upfront, to let local properties override.
loadProperties(result);
} if (this.localProperties != null) {
for (Properties localProp : this.localProperties) {
CollectionUtils.mergePropertiesIntoMap(localProp, result);
}
} if (!this.localOverride) {
// Load properties from file afterwards, to let those properties override.
loadProperties(result);
} return result;
} /**
* Load properties into the given instance.
* @param props the Properties instance to load into
* @throws IOException in case of I/O errors
* @see #setLocations
*/
protected void loadProperties(Properties props) throws IOException {
if (this.locations != null) {
for (Resource location : this.locations) {
if (logger.isInfoEnabled()) {
logger.info("Loading properties file from " + location);
}
try {
PropertiesLoaderUtils.fillProperties(
props, new EncodedResource(location, this.fileEncoding), this.propertiesPersister);
}
catch (IOException ex) {
if (this.ignoreResourceNotFound) {
if (logger.isWarnEnabled()) {
logger.warn("Could not load properties from " + location + ": " + ex.getMessage());
}
}
else {
throw ex;
}
}
}
}
} }

应用

spring bean 配置文件中

<util:properties id="config" location="classpath:conf/config.properties"></util:properties>

java 常量文件中

package cn.zno.common.constants;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; @Component
public class ApplicationConstants { public static String SWAGGER_PATH; @Autowired(required = true)
public void setSWAGGER_PATH(@Value("#{config['swagger.path']}") String SWAGGER_PATH) {
ApplicationConstants.SWAGGER_PATH = SWAGGER_PATH;
}
}

高级用法

util: 命名空间是通过工厂bean 返回 java.util 包下的实例,交给spring 工厂管理

理解了原理就可以实现 java-based 配置

import java.io.IOException;
import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component; /**
* 说明:WeixinProperties
* 创建人:zxg
* 创建时间:2018-05-23
*/
@Component
public class WeixinProperties { public static String appsecret; public static String appid; public static String urlCheckcode; @Autowired
public void setAppsecret(@Value("#{weixin['appsecret']}") String appsecret) {
WeixinProperties.appsecret = appsecret;
} @Autowired
public void setAppid(@Value("#{weixin['appid']}") String appid) {
WeixinProperties.appid = appid;
} @Autowired
public void setUrlCheckcode(@Value("#{weixin['url.checkcode']}") String urlCheckcode) {
WeixinProperties.urlCheckcode = urlCheckcode;
} @Bean("weixin")
public Properties getProperties() {
Properties properties = new Properties();
try {
properties.load(new ClassPathResource("env/weixin.properties").getInputStream());
} catch (IOException e) {
throw new RuntimeException("读取属性文件", e);
}
return properties;
}
}

此文件可自动生成

//TODO 类的加载优先级需要调高

util:properties的更多相关文章

  1. Android中使用java.util.Properties犯的错

    今天尝试使用java.util.Properties来保存应用配置,然而遇到了好几个问题,对于熟悉此内容的来说可能都是猪一样的错误,但难免有像我一样的新手再次遇到,希望此文能有所帮助. 错误1 jav ...

  2. JavaSE配置文件java.util.Properties【单例模式Singleton】

    如果不是放在src文件夹里面,则: p.load(new BufferedInputStream(new FileInputStream("tank.properties"))); ...

  3. 关于java.util.Properties读取中文乱码的正确解决方案(不要再用native2ascii.exe了)

    从Spring框架流行后,几乎根本不用自己写解析配置文件的代码了,但近日一个基础项目(实在是太基础,不能用硕大繁琐的Spring), 碰到了用java.util.Properties读取中文内容(UT ...

  4. util:properties与context:property-placeholder

    spring 使用注解装配的Bean如何使用property-placeholder属性配置中的值 这个问题不大不小,以前偷懒凡是碰到需要引用属性文件中的类时就改用xml来配置. 今天看了下sprin ...

  5. 使用java.util.Properties类读写配置文件

    J2SE 1.5 以前的版本要求直接使用 XML 解析器来装载配置文件并存储设置,虽说也并非难事,相比 java.util.Properties却要做额外的解析工作.而java.util.Proper ...

  6. java.util.Properties工具类

    import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import ...

  7. java.util.Properties类 学习笔记

    学习目标:   1.认识properties文件,理解其含义,会正确创建properties文件. 2.会使用java.util.Properties类来操作properties文件. 3.掌握相对路 ...

  8. 属性集合java.util.Properties

    属性集合java.util.Properties java.util.Properties集合 extends Hashtable<k, v> implements Map<k, v ...

  9. Java.util.properties读取配置文件分析

    Java.util.properties API链接: https://docs.oracle.com/javase/8/docs/api/java/util/Properties.html Clas ...

  10. 【Java笔记】配置文件java.util.Properties类的使用

    配置文件的路径:项目名/src/main/resources/mmall.properties mmall.properties的内容是键值对.例如假设写了ftp服务器的一些信息. ftp.serve ...

随机推荐

  1. vim之vundle

    git clone https://github.com/gmarik/vundle.git ~/.vim/bundle/vundle,下载到本地 gvim ~/.vimrc set nocompat ...

  2. 黄聪:[C#]如何获取变量的名字,不是值,是名称。返回名字的字符串

    找了好久,最后在国外的论坛找到了解决办法,直接贴代码吧. 方法一: public static class MemberInfoGetting { public static string GetMe ...

  3. (转)C#与Outlook交互收发邮件

    本文转载自:http://www.cnblogs.com/Moosdau/archive/2012/03/11/2390729.html .Net对POP3邮件系统已经集成了相应的功能,但是如果是基于 ...

  4. UI“三重天”之appium(一)

    官方介绍: Appium is an open-source tool for automating native, mobile web, and hybrid applications on iO ...

  5. dd命令的conv=fsync,oflag=sync/dsync

    conv的参数有 1.sync Pad every input block to size of 'ibs' with trailing zero bytes. When used with 'blo ...

  6. Windows 程序 dump 崩溃调试

    Windows 程序捕获崩溃异常 生成dump 概述 事情的起因是,有个同事开发的程序,交付的版本程序,会偶尔随机崩溃了. 悲催的是没有输出log,也没有输出dump文件. 我建议他给程序代码加个异常 ...

  7. 清除MAC 可清除空间

    一.首先:查到了官方解释 https://support.apple.com/zh-cn/HT202867官方说 在 macOS Sierra 中,当您打开优化 Mac 储存空间时,会显示“可清除”内 ...

  8. windows拖动文件到Ubuntu

    只需要安装 sudo apt install lrzsz

  9. web.xml中配置spring.xml的三种方式

    我们知道spring在web.xml中可以有三种方式来配置其xml路径:org.springframework.web.servlet.DispatcherServletorg.springframe ...

  10. sudo免密码

    很多都是修改/etc/sudoers权限为740再加上一句 ALL=NOPASSWD:ALL 或者加一句 yourname ALL=(ALL) NOPASSWD: ALL 然后权限改回440 先说第一 ...