Access properties file programmatically with Spring?

前端 未结 15 1614
说谎
说谎 2020-11-27 09:37

We use the code below to inject Spring beans with properties from a properties file.



        
相关标签:
15条回答
  • 2020-11-27 09:48

    How about PropertiesLoaderUtils?

    Resource resource = new ClassPathResource("/my.properties");
    Properties props = PropertiesLoaderUtils.loadProperties(resource);
    
    0 讨论(0)
  • 2020-11-27 09:53

    You can get your properties through Environment class. As documentation stands:

    Properties play an important role in almost all applications, and may originate from a variety of sources: properties files, JVM system properties, system environment variables, JNDI, servlet context parameters, ad-hoc Properties objects, Maps, and so on. The role of the environment object with relation to properties is to provide the user with a convenient service interface for configuring property sources and resolving properties from them.

    Having Environment as a env variable, simply call:

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

    You can get your 'raw' properties through:

    env.getProperty("your-property")
    

    It will search through all properties source that spring has registered.

    You can either obtain Environment through:

    • inject ApplicationContext by implementing ApplicationContextAware and then call getEnvironment() on context
    • implement EnvironmentAware.

    It's obtain through implementation of a class because properties are resolved on early stage of application startup, as they may be required for bean construction.

    Read more on documentation: spring Environment documentation

    0 讨论(0)
  • 2020-11-27 09:53

    This is the finest way I got it to work:

    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);
        }
    }
    
    0 讨论(0)
  • 2020-11-27 09:54

    I have done this and it has worked.

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

    That should work.

    0 讨论(0)
  • 2020-11-27 09:55

    This will resolve any nested properties.

    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();
    }
    
    0 讨论(0)
  • 2020-11-27 09:57
    create .properties file in classpath of your project and add path configuration in xml`<context:property-placeholder location="classpath*:/*.properties" />`
    

    in servlet-context.xml after that u can directly use your file everywhere

    0 讨论(0)
提交回复
热议问题