
com.buabook.spring.properties.PropertyLoader Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of spring-common Show documentation
Show all versions of spring-common Show documentation
Spring functionality (c) 2016 Sport Trades Ltd
The newest version!
package com.buabook.spring.properties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.AbstractBeanFactory;
import com.google.common.base.Strings;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
/**
* Spring Properties Programmatic Access
* Provides programmatic access to the Spring properties defined in the application.
* NOTE: By default, this class caches results indefinitely once queried from the property file. Override
* {@link #buildNewCache()} if you wish to change this behaviour.
* (c) 2015 Sport Trades Ltd
*
* @author Jas Rajasansir
* @version 1.0.0
* @since 6 Oct 2015
*/
public class PropertyLoader {
private final AbstractBeanFactory beanFactory;
private final LoadingCache cache;
/** @see PropertyLoader */
public PropertyLoader(AbstractBeanFactory beanFactory) {
this.beanFactory = beanFactory;
this.cache = buildNewCache();
}
/**
* NOTE: It is recommended in most cases to use Spring's {@link Value} annotation to load
* property configuration. This method is supplied in the rare cases that you need to programmatically
* define the key.
* @param property The property name to load, without the Spring ${
and }
tags (these
* will be added automatically)
* @return The specified property value
*/
public String getProperty(String property) {
if(Strings.isNullOrEmpty(property))
return null;
return cache.getUnchecked(property);
}
/**
* Provides the cache to store properties loaded via the {@link AbstractBeanFactory}.
* This can be overridden if necessary to customise the cache. Use {@link #getCacheLoader()} as the {@link CacheLoader}.
* @see CacheBuilder
*/
protected LoadingCache buildNewCache() {
return CacheBuilder.newBuilder().build(getCacheLoader());
}
private String getPropertyFromSpring(String property) {
String propertyName = "${" + property + "}";
String propertyValue = "";
try {
propertyValue = beanFactory.resolveEmbeddedValue(propertyName);
} catch(IllegalArgumentException e) {
// If the property doesn't exist, an IllegalArgumentException will be thrown. We'll catch it and just return empty string
}
return propertyValue;
}
private CacheLoader getCacheLoader() {
return new CacheLoader() {
@Override
public String load(String key) throws Exception {
return getPropertyFromSpring(key);
}
};
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy