All Downloads are FREE. Search and download functionalities are using the official Maven repository.

me.paulschwarz.springdotenv.DotenvPropertySource Maven / Gradle / Ivy

There is a newer version: 4.0.0
Show newest version
package me.paulschwarz.springdotenv;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertyResolver;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;

public class DotenvPropertySource extends PropertySource {

  private static final Log logger = LogFactory.getLog(DotenvPropertySource.class);

  /** Name of the env {@link PropertySource}. */
  public static final String DOTENV_PROPERTY_SOURCE_NAME = "env";

  private static final String DEFAULT_PREFIX = "env.";

  private String prefix;

  public DotenvPropertySource(String name, DotenvConfig dotenvConfig) {
    super(name, new DotenvPropertyLoader(dotenvConfig));
  }

  public DotenvPropertySource(DotenvConfig dotenvConfig) {
    this(DOTENV_PROPERTY_SOURCE_NAME, dotenvConfig);

    this.prefix = dotenvConfig.getPrefixOptional().orElse(DEFAULT_PREFIX);
  }

  public DotenvPropertySource() {
    this(new DotenvConfig(null));
  }

  /**
   * Return the value associated with the given name, or {@code null} if not found.
   *
   * @param name the property to find
   * @see PropertyResolver#getRequiredProperty(String)
   */
  @Override
  public Object getProperty(String name) {
    if (!name.startsWith(prefix)) {
      return null;
    }

    if (logger.isTraceEnabled()) {
      logger.trace("Getting env property for '" + name + "'");
    }

    return getSource().getValue(name.substring(prefix.length()));
  }

  public static void addToEnvironment(ConfigurableEnvironment environment) {
    DotenvConfig dotenvConfig = new DotenvConfig(environment);
    logger.info("Initializing Dotenv with " + dotenvConfig);

    environment
        .getPropertySources()
        .addAfter(
            StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
            new DotenvPropertySource(dotenvConfig));

    logger.trace("DotenvPropertySource added to Environment");
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy