2016-09-19 8 views
0

스프링 부트 설명서를 통해 externalized configuration을 읽었습니다. 그러면 자동으로 src/main/resources/application.properties 파일을로드 한 다음 주석을 사용하는 bean 특성.스프링 부트의 java.util.Properties에 application.properties 파일로드하기

그러나 을 application.properties의 속성으로 빌드하는 데 사용할 수있는 일반 PropertyHelper 클래스를 갖고 싶습니다. 이 작업을 수행 할 수 있습니까?

우리는 현재 수동으로 다음과 같이이 달성됩니다

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

또는 할 수있는 모든 값을 포함하는 속성 형 콩은 그냥 자동으로 묶어 환경 파일에서 – rorschach

+1

'Environment'를 사용하면 속성을 가져올 수 있지만 모든 속성 목록이 없습니다. 당신은 단지'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

다음은 Spring 환경에서 Properties 객체를 파생하는 방법입니다. 필자는 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; 
} 

그러나 순서는 중요 할 수 있습니다. 다른 특성 다음에 시스템 특성을로드하여 응용 프로그램 특성을 대체 할 수 있습니다. 이 경우, "systemProperties"을 선택하는 source.getName()를 사용하여 좀 더 제어 코드를 추가

@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; 
} 
관련 문제