Access properties file programmatically with Spring?

前端 未结 15 1651
说谎
说谎 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: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);
        }
    }
    

提交回复
热议问题