util:properties

示例

<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;
                    }
                }
            }
        }
    }

}

时间: 2024-12-27 09:07:46

util:properties的相关文章

&lt;util:properties id=&quot;propertiesReader&quot; location=&quot;classpath:jdbc.properties&quot;/&gt;

Property or field 'jdbc' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public? // jdbc.username=scott jdbc.password=TIGER jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl jdbc.driver=orac

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

PropertyMgr.java 1 package config; 2 3 import java.io.IOException; 4 import java.util.Properties; 5 6 public class PropertyMgr { 7 8 private static final Properties props = new Properties(); 9 10 static { 11 try { 12 props.load(PropertyMgr.class.getC

java.util.Properties类

Properties类很常用么,几乎每个项目,从j2se到j2ee每个项目都没离开过他,就算是jsp+servlet+jdbc的东西,jdbc的配置信息也是写Properties,国际化也是Properties,cdn也是Properties,memcached也是 Properties.总之java.utils.*无所不用,不所不在.. 小记下Properties: java.util.Properties是对properties这类配置文件的映射.支持key-value类型和xml类型两种.

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

今天尝试使用java.util.Properties来保存应用配置,然而遇到了好几个问题,对于熟悉此内容的来说可能都是猪一样的错误,但难免有像我一样的新手再次遇到,希望此文能有所帮助. 错误1 java.io.IOException: open failed: EROFS (Read-only file system)at java.io.File.createNewFile(File.java:940) 出错代码: 1 File file = new File("config.properti

使用java.util.Properties快速导入配置文件

1.java.util.Properties类继承关系 Properties类表示一组持久属性.属性可以被保存到流或从流中加载.属性列表中的每一个键及其相应的值是一个字符串. 继承关系: java.lang.Object java.util.Dictionary<K,V> java.util.Hashtable<Object,Object> java.util.Properties public class Properties extends Hashtable<Objec

java.util.properties

http://gimgen1026.iteye.com/blog/152023 Properties 类已不是新东西了,它在 Java 编程的早期就有了,并且几乎没有什么变化.J2SE 的 Tiger 版本增强了这个类,不仅可以用它在单独一行中指定用等号分隔的多个键-值对,还可以用XML 文件装载和保存这些键-值对.在 驯服 Tiger的这一期文章中,John Zukowski 展示了如何驾驭这匹新一代的“役马”. J2SE 1.5 以前的版本要求直接使用 XML 解析器来装载配置文件并存储设置

JDK源码学习(9)- java.util.Properties实例与源码

java.util.Properties说明. 该类主要是读取属性配置文件,两种文件类型:普通文件格式为key = value:xml文件. 1)key = value示例如下: public class TestProperties { public static void main(String[] args) { Properties properties = new Properties(); FileInputStream fileInputStream; try { fileInpu

工作积累(二)——使用java.util.ResourceBundle和java.util.Properties实现常量功能

在 Java 中我们往往通过定义常量来使用一些值,方便我们进行修改配置,如: public classConstant {   public static final String IMG_ORI_PATH = "ori/";   public static final String IMG_THUMB_PATH = "thumb/";   -- } 这样我们在其他类中可以直接使用 Constant.IMG_ORI_PATH 来代替 "ori/"

util:properties与context:property-placeholder

spring 使用注解装配的Bean如何使用property-placeholder属性配置中的值 这个问题不大不小,以前偷懒凡是碰到需要引用属性文件中的类时就改用xml来配置. 今天看了下spring 3 的El,看来有更简单的解决方式 在XML配置文件中配置一个util:properties context:property-placeholder location="/WEB-INF/config.properties"/> <util:properties id=&