001/* 002 * Copyright 2012-2018 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.boot.origin; 018 019import org.springframework.core.env.PropertySource; 020import org.springframework.util.Assert; 021 022/** 023 * {@link Origin} from a {@link PropertySource}. 024 * 025 * @author Phillip Webb 026 * @since 2.0.0 027 */ 028public class PropertySourceOrigin implements Origin { 029 030 private final PropertySource<?> propertySource; 031 032 private final String propertyName; 033 034 /** 035 * Create a new {@link PropertySourceOrigin} instance. 036 * @param propertySource the property source 037 * @param propertyName the name from the property source 038 */ 039 public PropertySourceOrigin(PropertySource<?> propertySource, String propertyName) { 040 Assert.notNull(propertySource, "PropertySource must not be null"); 041 Assert.hasLength(propertyName, "PropertyName must not be empty"); 042 this.propertySource = propertySource; 043 this.propertyName = propertyName; 044 } 045 046 /** 047 * Return the origin {@link PropertySource}. 048 * @return the origin property source 049 */ 050 public PropertySource<?> getPropertySource() { 051 return this.propertySource; 052 } 053 054 /** 055 * Return the property name that was used when obtaining the original value from the 056 * {@link #getPropertySource() property source}. 057 * @return the origin property name 058 */ 059 public String getPropertyName() { 060 return this.propertyName; 061 } 062 063 @Override 064 public String toString() { 065 return "\"" + this.propertyName + "\" from property source \"" 066 + this.propertySource.getName() + "\""; 067 } 068 069 /** 070 * Get an {@link Origin} for the given {@link PropertySource} and 071 * {@code propertyName}. Will either return an {@link OriginLookup} result or a 072 * {@link PropertySourceOrigin}. 073 * @param propertySource the origin property source 074 * @param name the property name 075 * @return the property origin 076 */ 077 public static Origin get(PropertySource<?> propertySource, String name) { 078 Origin origin = OriginLookup.getOrigin(propertySource, name); 079 return (origin != null) ? origin : new PropertySourceOrigin(propertySource, name); 080 } 081 082}