6 Ocak 2020 Pazartesi

SpringContext Environment Arayüzü

Giriş
Şu satırı dahil ederiz.
import org.springframework.core.env.Environment;
Açıklaması şöyle. Yani sadece System.getenv("...") çağrısınu kullanmaz. Bir sürü yere daha bakarak arama yapar.
Properties play an important role in almost all applications, and may originate from a variety of sources: properties files, JVM system properties, system environment variables, JNDI, servlet context parameters, ad-hoc Properties objects, Maps, and so on. The role of the environment object with relation to properties is to provide the user with a convenient service interface for configuring property sources and resolving properties from them. 
getActiveProfiles metodu
Şöyle yaparız.
@Autowired
Environment env;

// If the environment is dev
if(env.getActiveProfiles()[0].equalsIgnoreCase("dev")) {
  ...
}
getProperty metodu
Örnek
Şöyle yaparız.
@SpringBootApplication
public class Application implements CommandLineRunner {

  @Autowired
  private Environment env;

  @Override
  public void run(String... args) throws Exception {

    logger.info("{}", env.getProperty("JAVA_HOME"));
    logger.info("{}", env.getProperty("app.name"));
  }
  ...
}
getRequiredProperty metodu
Şöyle yaparız.
environment.getRequiredProperty("jdbc.driverClassName")

Hiç yorum yok:

Yorum Gönder