2016-09-19 2 views
0

Я прочитал документацию Spring Boot для externalized configuration, и я вижу, что он автоматически загружает файл src/main/resources/application.properties, который затем можно подключить к свойства компонента с помощью аннотации.Загрузка файла application.properties в java.util.Properties в Spring Boot

Однако я хочу иметь общий класс PropertyHelper, который может быть использован для построения java.util.Properties со свойствами в application.properties. Это можно сделать?

Мы в настоящее время достижение этой цели вручную, как показано ниже:

public class PropertyHelper { 

    private static Properties loadProperties() { 
     try { 

      String propsName = "application.properties"; 
      InputStream propsStream = PropertyHelper.class 
        .getClassLoader().getResourceAsStream(propsName); 
      if (propsStream == null) { 
       throw new IOException("Could not read config properties"); 
      } 

      Properties props = new Properties(); 
      props.load(propsStream); 
+0

добавить косую черту перед 'application.properties' – Jens

+3

Или вы можете просто autowire окружающей среды, который является Свойства типа боб, содержащий все значения из файла – rorschach

+1

С 'Environment' вы _can_ получите свойства, но у него нет списка всех свойств. вы можете использовать 'env.getProperty (" propertyName ")', чтобы получить свойство –

ответ

1

Вы можете создать Wrapper вокруг среды, которая будет возвращать готовый к использованию PropertySource:

Вы бы использовать его таким образом:

@PropertySource(name="myName", value="classpath:/myName.properties") 
public class YourService { 

    @Autowired 
    private CustomMapProperties customMapProperties; 
    ... 
    MapPropertySource mapPropertySource = customMapProperties.getMapProperties("myName"); 
    for(String key: mapPropertySource.getSource().keySet()){ 
     System.out.println(mapPropertySource.getProperty(key)); 
    } 

CustomMapProperties вводят Environment и возвращает запрос & загруженного файла свойство основано на его названии:

@Component 
public class CustomMapProperties { 

    @Autowired 
    private Environment env; 

    public MapPropertySource getMapProperties(String name) { 
     for (Iterator<?> it = ((AbstractEnvironment) env).getPropertySources().iterator(); it.hasNext();) { 
      Object propertySource = it.next(); 
      if (propertySource instanceof MapPropertySource 
        && ((MapPropertySource) propertySource).getName().equals(name)) { 
       return (MapPropertySource) propertySource; 
      } 
     } 
     return null; 
    } 
} 
0

Вот как я вывести объект Properties из среды Spring,. Я ищу источники ресурсов типа java.util.Properties, которые в моем случае дадут мне свойства системы и свойства приложения.

@Resource 
private Environment environment; 


@Bean 
public Properties properties() { 
    Properties properties = new Properties(); 

    for (PropertySource<?> source : ((ConfigurableEnvironment) environment).getPropertySources()) { 
     if (source.getSource() instanceof Properties) { 
      log.info("Loading properties from property source " + source.getName()); 
      Properties props = (Properties) source.getSource(); 
      properties.putAll(props); 
     } 
    } 

    return properties; 
} 

Обратите внимание, что заказ может быть значительным; вы, вероятно, захотите загрузить свойства системы после других свойств, чтобы они могли переопределить свойства приложения. В этом случае добавьте еще немного код управления с помощью source.getName(), чтобы выбрать «systemProperties»:

@Bean 
public Properties properties() { 
    Properties properties = new Properties(); 

    Properties systemProperties = null; 

    for (PropertySource<?> source : ((ConfigurableEnvironment) environment).getPropertySources()) { 
     if (source.getSource() instanceof Properties) { 
      if ("systemProperties".equalsIgnoreCase(source.getName())) { 
       log.info("Found system properties from property source " + source.getName()); 
       systemProperties = (Properties) source.getSource(); 
      } else { 
       log.info("Loading properties from property source " + source.getName()); 
       Properties props = (Properties) source.getSource(); 
       properties.putAll(props); 
      } 
     } 
    } 

    // Load this at the end so they can override application properties. 
    if (systemProperties != null) { 
     log.info("Loading system properties from property source."); 
     properties.putAll(systemProperties); 
    } 

    return properties; 
} 
Смежные вопросы