다음은 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;
}
는'전에 슬래시를 추가 application.properties' – Jens
또는 할 수있는 모든 값을 포함하는 속성 형 콩은 그냥 자동으로 묶어 환경 파일에서 – rorschach
'Environment'를 사용하면 속성을 가져올 수 있지만 모든 속성 목록이 없습니다. 당신은 단지'env.getProperty ("propertyName")'을 사용하여 속성을 얻을 수있다. –