Spring CompositePropertySource

  • Author: HuiFer
  • 源码阅读仓库: SourceHot-spring

  • 全路径: org.springframework.core.env.CompositePropertySource

  • 整体代码如下

  1. public class CompositePropertySource extends EnumerablePropertySource<Object> {
  2. /**
  3. * set 集合
  4. */
  5. private final Set<PropertySource<?>> propertySources = new LinkedHashSet<>();
  6. /**
  7. * Create a new {@code CompositePropertySource}.
  8. * @param name the name of the property source
  9. */
  10. public CompositePropertySource(String name) {
  11. super(name);
  12. }
  13. @Override
  14. @Nullable
  15. public Object getProperty(String name) {
  16. // 循环
  17. for (PropertySource<?> propertySource : this.propertySources) {
  18. // 获取存储内容
  19. Object candidate = propertySource.getProperty(name);
  20. if (candidate != null) {
  21. return candidate;
  22. }
  23. }
  24. return null;
  25. }
  26. @Override
  27. public boolean containsProperty(String name) {
  28. for (PropertySource<?> propertySource : this.propertySources) {
  29. // 是否存在name
  30. if (propertySource.containsProperty(name)) {
  31. return true;
  32. }
  33. }
  34. return false;
  35. }
  36. @Override
  37. public String[] getPropertyNames() {
  38. Set<String> names = new LinkedHashSet<>();
  39. for (PropertySource<?> propertySource : this.propertySources) {
  40. // 类型不同抛出异常
  41. if (!(propertySource instanceof EnumerablePropertySource)) {
  42. throw new IllegalStateException(
  43. "Failed to enumerate property names due to non-enumerable property source: " + propertySource);
  44. }
  45. // 批量添加
  46. names.addAll(Arrays.asList(((EnumerablePropertySource<?>) propertySource).getPropertyNames()));
  47. }
  48. // 转换成 array
  49. return StringUtils.toStringArray(names);
  50. }
  51. /**
  52. * Add the given {@link PropertySource} to the end of the chain.
  53. * @param propertySource the PropertySource to add
  54. */
  55. public void addPropertySource(PropertySource<?> propertySource) {
  56. this.propertySources.add(propertySource);
  57. }
  58. /**
  59. * Add the given {@link PropertySource} to the start of the chain.
  60. * @param propertySource the PropertySource to add
  61. * @since 4.1
  62. */
  63. public void addFirstPropertySource(PropertySource<?> propertySource) {
  64. // 头插
  65. List<PropertySource<?>> existing = new ArrayList<>(this.propertySources);
  66. this.propertySources.clear();
  67. this.propertySources.add(propertySource);
  68. this.propertySources.addAll(existing);
  69. }
  70. /**
  71. * Return all property sources that this composite source holds.
  72. * @since 4.1.1
  73. */
  74. public Collection<PropertySource<?>> getPropertySources() {
  75. return this.propertySources;
  76. }
  77. @Override
  78. public String toString() {
  79. return getClass().getSimpleName() + " {name='" + this.name + "', propertySources=" + this.propertySources + "}";
  80. }
  81. }