使用Spring以编程方式访问属性文件?

时间:2009-11-20 15:22:01

标签: spring properties

我们使用下面的代码为Spring bean注入属性文件中的属性。

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations" value="classpath:/my.properties"/>
</bean>

<bean id="blah" class="abc">
    <property name="path" value="${the.path}"/>
</bean>

我们有办法以编程方式访问属性吗?我正在尝试做一些没有依赖注入的代码。所以我想要一些像这样的代码:

PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer();
props.load("classpath:/my.properties");
props.get("path");

17 个答案:

答案 0 :(得分:159)

PropertiesLoaderUtils怎么样?

Resource resource = new ClassPathResource("/my.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);

答案 1 :(得分:50)

如果您只想从代码访问占位符值,则会有@Value注释:

@Value("${settings.some.property}")
String someValue;

访问占位符从SPEL使用以下语法:

#('${settings.some.property}')

要将配置公开给已关闭SPEL的视图,可以使用此技巧:

package com.my.app;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.stereotype.Component;

@Component
public class PropertyPlaceholderExposer implements Map<String, String>, BeanFactoryAware {  
    ConfigurableBeanFactory beanFactory; 

    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = (ConfigurableBeanFactory) beanFactory;
    }

    protected String resolveProperty(String name) {
        String rv = beanFactory.resolveEmbeddedValue("${" + name + "}");

        return rv;
    }

    @Override
    public String get(Object key) {
        return resolveProperty(key.toString());
    }

    @Override
    public boolean containsKey(Object key) {
        try {
            resolveProperty(key.toString());
            return true;
        }
        catch(Exception e) {
            return false;
        }
    }

    @Override public boolean isEmpty() { return false; }
    @Override public Set<String> keySet() { throw new UnsupportedOperationException(); }
    @Override public Set<java.util.Map.Entry<String, String>> entrySet() { throw new UnsupportedOperationException(); }
    @Override public Collection<String> values() { throw new UnsupportedOperationException(); }
    @Override public int size() { throw new UnsupportedOperationException(); }
    @Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(); }
    @Override public void clear() { throw new UnsupportedOperationException(); }
    @Override public String put(String key, String value) { throw new UnsupportedOperationException(); }
    @Override public String remove(Object key) { throw new UnsupportedOperationException(); }
    @Override public void putAll(Map<? extends String, ? extends String> t) { throw new UnsupportedOperationException(); }
}

然后使用曝光器将属性公开给视图:

<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="tilesViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
    <property name="attributesMap">
        <map>
            <entry key="config">
                <bean class="com.my.app.PropertyPlaceholderExposer" />
            </entry>
        </map>
    </property>
</bean>

然后在视图中,使用这样的公开属性:

${config['settings.some.property']}

此解决方案的优势在于您可以依赖标准占位符 上下文注入的实现:property-placeholder标记。

现在作为最后一点,如果您确实需要捕获所有占位符属性及其值,则必须通过StringValueResolver管道它们以确保占位符在预期的属性值内工作。以下代码将执行此操作。

package com.my.app;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.util.StringValueResolver;

public class AppConfig extends PropertyPlaceholderConfigurer implements Map<String, String> {

    Map<String, String> props = new HashMap<String, String>();

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props)
            throws BeansException {

        this.props.clear();
        for (Entry<Object, Object> e: props.entrySet())
            this.props.put(e.getKey().toString(), e.getValue().toString());

        super.processProperties(beanFactory, props);
    }

    @Override
    protected void doProcessProperties(ConfigurableListableBeanFactory beanFactoryToProcess,
            StringValueResolver valueResolver) {

        super.doProcessProperties(beanFactoryToProcess, valueResolver);

        for(Entry<String, String> e: props.entrySet())
            e.setValue(valueResolver.resolveStringValue(e.getValue()));
    }

    // Implement map interface to access stored properties
    @Override public Set<String> keySet() { return props.keySet(); }
    @Override public Set<java.util.Map.Entry<String, String>> entrySet() { return props.entrySet(); }
    @Override public Collection<String> values() { return props.values(); }
    @Override public int size() { return props.size(); }
    @Override public boolean isEmpty() { return props.isEmpty(); }
    @Override public boolean containsValue(Object value) { return props.containsValue(value); }
    @Override public boolean containsKey(Object key) { return props.containsKey(key); }
    @Override public String get(Object key) { return props.get(key); }
    @Override public void clear() { throw new UnsupportedOperationException(); }
    @Override public String put(String key, String value) { throw new UnsupportedOperationException(); }
    @Override public String remove(Object key) { throw new UnsupportedOperationException(); }
    @Override public void putAll(Map<? extends String, ? extends String> t) { throw new UnsupportedOperationException(); }
}

答案 2 :(得分:49)

CREDIT Programmatic access to properties in Spring without re-reading the properties file

我发现了一个很好的实现,可以在spring中以编程方式访问属性,而无需重新加载spring已经加载的相同属性。 [此外,不需要对源中的属性文件位置进行硬编码]

通过这些更改,代码看起来更清晰&amp;更易于维护。

这个概念非常简单。只需扩展spring默认属性占位符(PropertyPlaceholderConfigurer)并捕获它在本地变量中加载的属性

public class SpringPropertiesUtil extends PropertyPlaceholderConfigurer {

    private static Map<String, String> propertiesMap;
    // Default as in PropertyPlaceholderConfigurer
    private int springSystemPropertiesMode = SYSTEM_PROPERTIES_MODE_FALLBACK;

    @Override
    public void setSystemPropertiesMode(int systemPropertiesMode) {
        super.setSystemPropertiesMode(systemPropertiesMode);
        springSystemPropertiesMode = systemPropertiesMode;
    }

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {
        super.processProperties(beanFactory, props);

        propertiesMap = new HashMap<String, String>();
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            String valueStr = resolvePlaceholder(keyStr, props, springSystemPropertiesMode);
            propertiesMap.put(keyStr, valueStr);
        }
    }

    public static String getProperty(String name) {
        return propertiesMap.get(name).toString();
    }

}

用法示例

SpringPropertiesUtil.getProperty("myProperty")

Spring配置更改

<bean id="placeholderConfigMM" class="SpringPropertiesUtil">
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
    <property name="locations">
    <list>
        <value>classpath:myproperties.properties</value>
    </list>
    </property>
</bean>

希望这有助于解决您遇到的问题

答案 3 :(得分:44)

我已经完成了这项工作并且有效。

Properties props = PropertiesLoaderUtils.loadAllProperties("my.properties");
PropertyPlaceholderConfigurer props2 = new PropertyPlaceholderConfigurer();
props2.setProperties(props);

这应该有效。

答案 4 :(得分:24)

您也可以使用spring utils,或通过PropertiesFactoryBean加载属性。

<util:properties id="myProps" location="classpath:com/foo/myprops.properties"/>

或:

<bean id="myProps" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="location" value="classpath:com/foo/myprops.properties"/>
</bean>

然后您可以使用以下方式在您的应用程序中选择它们:

@Resource(name = "myProps")
private Properties myProps;

并在配置中另外使用这些属性:

<context:property-placeholder properties-ref="myProps"/>

这也在文档中:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#xsd-config-body-schemas-util-properties

答案 5 :(得分:9)

创建一个类如下

    package com.tmghealth.common.util;

    import java.util.Properties;

    import org.springframework.beans.BeansException;

    import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

    import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

    import org.springframework.context.annotation.Configuration;

    import org.springframework.context.annotation.PropertySource;

    import org.springframework.stereotype.Component;


    @Component
    @Configuration
    @PropertySource(value = { "classpath:/spring/server-urls.properties" })
    public class PropertiesReader extends PropertyPlaceholderConfigurer {

        @Override
        protected void processProperties(
                ConfigurableListableBeanFactory beanFactory, Properties props)
                throws BeansException {
            super.processProperties(beanFactory, props);

        }

    }

然后,无论您想要访问某个属性,都可以使用

    @Autowired
        private Environment environment;
    and getters and setters then access using 

    environment.getProperty(envName
                    + ".letter.fdi.letterdetails.restServiceUrl");

- 在访问者类中编写getter和setter

    public Environment getEnvironment() {
            return environment;
        }`enter code here`

        public void setEnvironment(Environment environment) {
            this.environment = environment;
        }

答案 6 :(得分:3)

如您所知,较新版本的Spring不使用PropertyPlaceholderConfigurer,现在使用另一个名为PropertySourcesPlaceholderConfigurer的噩梦构造。如果你试图从代码中获得已解析的属性,并希望Spring团队在很久以前给我们一个方法来做这个,那么就投票给这篇文章吧! ...因为这是你如何做到的新方式:

Subclass PropertySourcesPlaceholderConfigurer:

public class SpringPropertyExposer extends PropertySourcesPlaceholderConfigurer {

    private ConfigurableListableBeanFactory factory;

    /**
     * Save off the bean factory so we can use it later to resolve properties
     */
    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,
            final ConfigurablePropertyResolver propertyResolver) throws BeansException {
        super.processProperties(beanFactoryToProcess, propertyResolver);

        if (beanFactoryToProcess.hasEmbeddedValueResolver()) {
            logger.debug("Value resolver exists.");
            factory = beanFactoryToProcess;
        }
        else {
            logger.error("No existing embedded value resolver.");
        }
    }

    public String getProperty(String name) {
        Object propertyValue = factory.resolveEmbeddedValue(this.placeholderPrefix + name + this.placeholderSuffix);
        return propertyValue.toString();
    }
}

要使用它,请确保在@Configuration中使用您的子类并保存对它的引用以供以后使用。

@Configuration
@ComponentScan
public class PropertiesConfig {

    public static SpringPropertyExposer commonEnvConfig;

    @Bean(name="commonConfig")
    public static PropertySourcesPlaceholderConfigurer commonConfig() throws IOException {
        commonEnvConfig = new SpringPropertyExposer(); //This is a subclass of the return type.
        PropertiesFactoryBean commonConfig = new PropertiesFactoryBean();
        commonConfig.setLocation(new ClassPathResource("META-INF/spring/config.properties"));
        try {
            commonConfig.afterPropertiesSet();
        }
        catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
        commonEnvConfig.setProperties(commonConfig.getObject());
        return commonEnvConfig;
    }
}

用法:

Object value = PropertiesConfig.commonEnvConfig.getProperty("key.subkey");

答案 7 :(得分:2)

这将解决所有嵌套属性。

public class Environment extends PropertyPlaceholderConfigurer {

/**
 * Map that hold all the properties.
 */
private Map<String, String> propertiesMap; 

/**
 * Iterate through all the Property keys and build a Map, resolve all the nested values before building the map.
 */
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {
    super.processProperties(beanFactory, props);

    propertiesMap = new HashMap<String, String>();
    for (Object key : props.keySet()) {
        String keyStr = key.toString();
        String valueStr = beanFactory.resolveEmbeddedValue(placeholderPrefix + keyStr.trim() + DEFAULT_PLACEHOLDER_SUFFIX);
        propertiesMap.put(keyStr, valueStr);
    }
} 

/**
 * This method gets the String value for a given String key for the property files.
 * 
 * @param name - Key for which the value needs to be retrieved.
 * @return Value
 */
public String getProperty(String name) {
    return propertiesMap.get(name).toString();
}

答案 8 :(得分:2)

只需注入Environment,然后对其调用getProperty。

@Autowired
private Environment env;

void foo() {
    env.getProperty("your.property");
}

答案 9 :(得分:2)

这有助于我:

ApplicationContextUtils.getApplicationContext().getEnvironment()

答案 10 :(得分:2)

这是另一个样本。

XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml"));
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.setLocation(new FileSystemResource("jdbc.properties"));
cfg.postProcessBeanFactory(factory);

答案 11 :(得分:1)

这篇文章还解释了如何访问属性:http://maciej-miklas.blogspot.de/2013/07/spring-31-programmatic-access-to.html

您可以访问spring property-placeholder在这样的spring bean上加载的属性:

@Named
public class PropertiesAccessor {

    private final AbstractBeanFactory beanFactory;

    private final Map<String,String> cache = new ConcurrentHashMap<>();

    @Inject
    protected PropertiesAccessor(AbstractBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    public  String getProperty(String key) {
        if(cache.containsKey(key)){
            return cache.get(key);
        }

        String foundProp = null;
        try {
            foundProp = beanFactory.resolveEmbeddedValue("${" + key.trim() + "}");
            cache.put(key,foundProp);
        } catch (IllegalArgumentException ex) {
           // ok - property was not found
        }

        return foundProp;
    }
}

答案 12 :(得分:0)

create .properties file in classpath of your project and add path configuration in xml`<context:property-placeholder location="classpath*:/*.properties" />`

在servlet-context.xml之后,你可以直接在任何地方使用你的文件

答案 13 :(得分:0)

请在您的spring配置文件中使用以下代码从应用程序的类路径加载文件

 <context:property-placeholder
    ignore-unresolvable="true" ignore-resource-not-found="false" location="classpath:property-file-name" />

答案 14 :(得分:0)

您可以通过Environment类来获取属性。就文档而言:

  

属性几乎在所有应用程序中都起着重要作用,并且可能源自各种来源:属性文件,JVM系统属性,系统环境变量,JNDI,Servlet上下文参数,临时属性对象,映射等。 。环境对象与属性相关的作用是为用户提供方便的服务界面,用于配置属性源并从中解析属性。

将环境作为env变量,只需调用:

env.resolvePlaceholders("${your-property:default-value}")

您可以通过以下方式获取“原始”属性:

env.getProperty("your-property")

它将搜索spring已注册的所有属性源。

您可以通过以下方式获取环境:

  • 通过实现ApplicationContextAware注入ApplicationContext,然后在上下文上调用getEnvironment()
  • 实现EnvironmentAware

它是通过类的实现获得的,因为属性是在应用程序启动的早期阶段解析的,因为它们可能是bean构建所必需的。

详细了解文档:spring Environment documentation

答案 15 :(得分:0)

这是我最好的工作方式:

package your.package;

import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

public class ApplicationProperties {

    private Properties properties;

    public ApplicationProperties() {
        // application.properties located at src/main/resource
        Resource resource = new ClassPathResource("/application.properties");
        try {
            this.properties = PropertiesLoaderUtils.loadProperties(resource);
        } catch (IOException ex) {
            Logger.getLogger(ApplicationProperties.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String getProperty(String propertyName) {
        return this.properties.getProperty(propertyName);
    }
}

答案 16 :(得分:0)

我知道这是一个旧线程,但是,对于那些在所有需要“立即”加载微服务并因此避免使用批注的微服务的情况下使用函数式方法的人来说,我认为该主题变得非常重要。 仍未解决的问题是最终加载我在application.yml中拥有的环境变量。

public class AppPropsLoader {
public static Properties load() {
  var propPholderConfig = new PropertySourcesPlaceHolderConfigurer();
  var yaml = new YamlPropertiesFactoryBean();
  ClassPathResource resource = new ClassPathResource("application.yml");
  Objects.requireNonNull(resource, "File application.yml does not exist");
  yaml.setResources(resource);
  Objects.requireNonNull(yaml.getObject(), "Configuration cannot be null");
  propPholderConfig.postProcessBeanFactory(new DefaultListableBeanFactory());
  propPholderConfig.setProperties(yaml.getObject());
  PropertySources appliedPropertySources = 
  propPholderConfig.getAppliedPropertySources();
  var resolver = new PropertySourcesPlaceholderResolver(appliedPropertySources);
  Properties resolvedProps = new Properties();
  for (Map.Entry<Object, Object> prop: yaml.getObject().entrySet()) {
    resolvedProps.setProperty((String)prop.getKey(), 
      getPropertyValue(resolver.resolvePlaceHolders(prop.getValue()));
  }
  return resolvedProps;
}
 static String getPropertyValue(Object prop) {
   var val = String.valueOf(prop);
   Pattern p = Pattern.compile("^(\\$\\{)([a-zA-Z0-9-._]+)(\\})$");
   Matcher m = p.matcher(val);
   if(m.matches()) {
    return System.getEnv(m.group(2));
  }
   return val;
 }
}