org.springframework.core.env.Environment类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(16.7k)|赞(0)|评价(0)|浏览(1306)

本文整理了Java中org.springframework.core.env.Environment类的一些代码示例,展示了Environment类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Environment类的具体详情如下:
包路径:org.springframework.core.env.Environment
类名称:Environment

Environment介绍

[英]Interface representing the environment in which the current application is running. Models two key aspects of the application environment: profiles and properties. Methods related to property access are exposed via the PropertyResolver superinterface.

A profile is a named, logical group of bean definitions to be registered with the container only if the given profile is active. Beans may be assigned to a profile whether defined in XML or via annotations; see the spring-beans 3.1 schema or the org.springframework.context.annotation.Profile annotation for syntax details. The role of the Environment object with relation to profiles is in determining which profiles (if any) are currently #getActiveProfiles, and which profiles (if any) should be #getDefaultProfiles.

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.

Beans managed within an ApplicationContext may register to be org.springframework.context.EnvironmentAware or @Inject the Environment in order to query profile state or resolve properties directly.

In most cases, however, application-level beans should not need to interact with the Environment directly but instead may have to have ${...}} property values replaced by a property placeholder configurer such as org.springframework.context.support.PropertySourcesPlaceholderConfigurer, which itself is EnvironmentAware and as of Spring 3.1 is registered by default when using .

Configuration of the environment object must be done through the ConfigurableEnvironment interface, returned from all AbstractApplicationContext subclass getEnvironment() methods. See ConfigurableEnvironment Javadoc for usage examples demonstrating manipulation of property sources prior to application context refresh().
[中]接口,表示当前应用程序运行的环境。为应用程序环境的两个关键方面建模:配置文件属性。与属性访问相关的方法通过PropertyResolver超级接口公开。
profile是一个命名的、逻辑的bean定义组,仅当给定的概要文件是active时,才会向容器注册。bean可以被分配给一个概要文件,不管是用XML定义的还是通过注释定义的;请参阅SpringBeans 3.1模式或组织。springframework。上下文注释。语法详细信息的概要文件注释。与概要文件相关的环境对象的作用是确定哪些概要文件(如果有)当前为#getActiveProfiles,哪些概要文件(如果有)应为#getDefaultProfiles。
属性在几乎所有的应用程序中都扮演着重要的角色,并且可能来自各种来源:属性文件、JVM系统属性、系统环境变量、JNDI、servlet上下文参数、特殊属性对象、映射等等。与属性相关的环境对象的作用是为用户提供一个方便的服务界面,用于配置属性源和解析属性。
ApplicationContext中管理的bean可以注册为org。springframework。上下文EnvironmentAware或@Inject环境,以便直接查询配置文件状态或解析属性。
然而,在大多数情况下,应用程序级bean不需要直接与环境交互,而是可能必须具有${…}由属性占位符配置器(如org)替换的属性值。springframework。上下文支持PropertySourcesPlaceholderConfigurer本身是环境感知的,从Spring3.1开始,在使用时默认注册。
环境对象的配置必须通过ConfigurableEnvironment接口完成,该接口由所有AbstractApplicationContext子类getEnvironment()方法返回。请参阅ConfigurableEnvironment Javadoc,了解演示在应用程序上下文刷新()之前操作属性源的用法示例。

代码示例

代码示例来源:origin: apache/incubator-dubbo-spring-boot-project

/**
 * Creates {@link ServiceAnnotationBeanPostProcessor} Bean
 *
 * @param environment {@link Environment} Bean
 * @return {@link ServiceAnnotationBeanPostProcessor}
 */
@ConditionalOnProperty(name = BASE_PACKAGES_PROPERTY_NAME)
@ConditionalOnClass(ConfigurationPropertySources.class)
@Bean
public ServiceAnnotationBeanPostProcessor serviceAnnotationBeanPostProcessor(Environment environment) {
  Set<String> packagesToScan = environment.getProperty(BASE_PACKAGES_PROPERTY_NAME, Set.class, emptySet());
  return new ServiceAnnotationBeanPostProcessor(packagesToScan);
}

代码示例来源:origin: spring-cloud/spring-cloud-config

public ConfigClientProperties(Environment environment) {
  String[] profiles = environment.getActiveProfiles();
  if (profiles.length == 0) {
    profiles = environment.getDefaultProfiles();
  }
  this.setProfile(StringUtils.arrayToCommaDelimitedString(profiles));
}

代码示例来源:origin: spring-projects/spring-framework

private void setupDomain(AnnotationMBeanExporter exporter, AnnotationAttributes enableMBeanExport) {
  String defaultDomain = enableMBeanExport.getString("defaultDomain");
  if (StringUtils.hasLength(defaultDomain) && this.environment != null) {
    defaultDomain = this.environment.resolvePlaceholders(defaultDomain);
  }
  if (StringUtils.hasText(defaultDomain)) {
    exporter.setDefaultDomain(defaultDomain);
  }
}

代码示例来源:origin: apache/incubator-dubbo-spring-boot-project

private void setDubboApplicationNameProperty(Environment environment, Map<String, Object> defaultProperties) {
  String springApplicationName = environment.getProperty(SPRING_APPLICATION_NAME_PROPERTY);
  if (StringUtils.hasLength(springApplicationName)
      && !environment.containsProperty(DUBBO_APPLICATION_NAME_PROPERTY)) {
    defaultProperties.put(DUBBO_APPLICATION_NAME_PROPERTY, springApplicationName);
  }
}

代码示例来源:origin: yu199195/myth

@Bean
public Consumer pushConsumer() throws MQClientException {
  Properties properties = new Properties();
  properties.setProperty(PropertyKeyConst.ConsumerId,env.getProperty("spring.aliyunmq.consumerId"));
  properties.setProperty(PropertyKeyConst.AccessKey,env.getProperty("spring.aliyunmq.accessKey"));
  properties.setProperty(PropertyKeyConst.SecretKey,env.getProperty("spring.aliyunmq.secretKey"));
  properties.setProperty(PropertyKeyConst.ONSAddr,env.getProperty("spring.aliyunmq.broker-url"));
  String topic = env.getProperty("spring.aliyunmq.topic");
  consumer.subscribe(topic, TAG, (message, consumeContext) -> {
    try {

代码示例来源:origin: netgloo/spring-boot-samples

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
 LocalContainerEntityManagerFactoryBean entityManagerFactory =
   env.getProperty("entitymanager.packagesToScan"));
 Properties additionalProperties = new Properties();
 additionalProperties.put(
   "hibernate.dialect", 
   env.getProperty("hibernate.dialect"));
 additionalProperties.put(
   "hibernate.show_sql", 
   env.getProperty("hibernate.show_sql"));
 additionalProperties.put(
   "hibernate.hbm2ddl.auto", 
   env.getProperty("hibernate.hbm2ddl.auto"));
 entityManagerFactory.setJpaProperties(additionalProperties);

代码示例来源:origin: org.springframework.boot/spring-boot

private Properties getPropertiesFromServices(Environment environment,
    JsonParser parser) {
  Properties properties = new Properties();
  try {
    String property = environment.getProperty(VCAP_SERVICES, "{}");
    Map<String, Object> map = parser.parseMap(property);
    extractPropertiesFromServices(properties, map);
  }
  catch (Exception ex) {
    logger.error("Could not parse VCAP_SERVICES", ex);
  }
  return properties;
}

代码示例来源:origin: jmdhappy/xxpay-master

@Bean(initMethod = "init", destroyMethod = "close")
public DruidDataSource dataSource() throws SQLException {
  if (StringUtils.isEmpty(propertyResolver.getProperty("url"))) {
    System.out.println("Your database connection pool configuration is incorrect!"
        + " Please check your Spring profile, current profiles are:"
        + Arrays.toString(environment.getActiveProfiles()));
    throw new ApplicationContextException(
        "Database connection pool is not configured correctly");
  }
  DruidDataSource druidDataSource = new DruidDataSource();
  druidDataSource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
  druidDataSource.setUrl(propertyResolver.getProperty("url"));
  druidDataSource.setUsername(propertyResolver.getProperty("username"));
  druidDataSource.setPassword(propertyResolver.getProperty("password"));
  druidDataSource.setInitialSize(Integer.parseInt(propertyResolver.getProperty("initialSize")));
  druidDataSource.setMinIdle(Integer.parseInt(propertyResolver.getProperty("minIdle")));
  druidDataSource.setMaxActive(Integer.parseInt(propertyResolver.getProperty("maxActive")));
  druidDataSource.setMaxWait(Integer.parseInt(propertyResolver.getProperty("maxWait")));
  druidDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(propertyResolver.getProperty("timeBetweenEvictionRunsMillis")));
  druidDataSource.setMinEvictableIdleTimeMillis(Long.parseLong(propertyResolver.getProperty("minEvictableIdleTimeMillis")));
  druidDataSource.setValidationQuery(propertyResolver.getProperty("validationQuery"));
  druidDataSource.setTestWhileIdle(Boolean.parseBoolean(propertyResolver.getProperty("testWhileIdle")));
  druidDataSource.setTestOnBorrow(Boolean.parseBoolean(propertyResolver.getProperty("testOnBorrow")));
  druidDataSource.setTestOnReturn(Boolean.parseBoolean(propertyResolver.getProperty("testOnReturn")));
  druidDataSource.setPoolPreparedStatements(Boolean.parseBoolean(propertyResolver.getProperty("poolPreparedStatements")));
  druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(propertyResolver.getProperty("maxPoolPreparedStatementPerConnectionSize")));
  druidDataSource.setFilters(propertyResolver.getProperty("filters"));
  return druidDataSource;
}

代码示例来源:origin: spring-cloud-incubator/spring-cloud-alibaba

@Bean
public AcmIntegrationProperties acmIntegrationProperties() {
  AcmIntegrationProperties acmIntegrationProperties = new AcmIntegrationProperties();
  String applicationName = environment.getProperty("spring.application.name");
  String applicationGroup = environment.getProperty("spring.application.group");
  Assert.isTrue(!StringUtils.isEmpty(applicationName),
      "'spring.application.name' must be configured in bootstrap.properties or bootstrap.yml/yaml...");
  acmIntegrationProperties.setApplicationName(applicationName);
  acmIntegrationProperties.setApplicationGroup(applicationGroup);
  acmIntegrationProperties.setActiveProfiles(environment.getActiveProfiles());
  acmIntegrationProperties.setAcmProperties(acmProperties);
  return acmIntegrationProperties;
}

代码示例来源:origin: spring-cloud-incubator/spring-cloud-alibaba

@Bean
  public GlobalTransactionScanner globalTransactionScanner() {

    String applicationName = applicationContext.getEnvironment()
        .getProperty("spring.application.name");

    String txServiceGroup = fescarProperties.getTxServiceGroup();

    if (StringUtils.isEmpty(txServiceGroup)) {
      txServiceGroup = applicationName + "-fescar-service-group";
      fescarProperties.setTxServiceGroup(txServiceGroup);
    }

    return new GlobalTransactionScanner(applicationName, txServiceGroup);
  }
}

代码示例来源:origin: apache/incubator-dubbo

private Set<String> resolvePackagesToScan(Set<String> packagesToScan) {
  Set<String> resolvedPackagesToScan = new LinkedHashSet<String>(packagesToScan.size());
  for (String packageToScan : packagesToScan) {
    if (StringUtils.hasText(packageToScan)) {
      String resolvedPackageToScan = environment.resolvePlaceholders(packageToScan.trim());
      resolvedPackagesToScan.add(resolvedPackageToScan);
    }
  }
  return resolvedPackagesToScan;
}

代码示例来源:origin: codingapi/tx-lcn

@Override
public void init() throws Exception {
  String name =  environment.getProperty("spring.application.name");
  String application = StringUtils.hasText(name) ? name : "application";
  String port =  environment.getProperty("server.port");
  Transactions.setApplicationId(String.format("%s:%s", application, port));
}

代码示例来源:origin: ctripcorp/apollo

@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
 if (!StringUtils.isEmpty(context.getEnvironment().getProperty("fat.titan.url"))) {
  return true;
 } else if (!StringUtils.isEmpty(context.getEnvironment().getProperty("uat.titan.url"))) {
  return true;
 } else if (!StringUtils.isEmpty(context.getEnvironment().getProperty("pro.titan.url"))) {
  return true;
 }
 return false;
}

代码示例来源:origin: spring-projects/spring-framework

@Override
  @Nullable
  public String getProperty(String key) {
    return this.source.getProperty(key);
  }
}

代码示例来源:origin: spring-projects/spring-framework

if (StringUtils.hasText(profileSpec)) {
  String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
      profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
  if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
    if (logger.isDebugEnabled()) {
      logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +

代码示例来源:origin: spring-cloud-incubator/spring-cloud-alibaba

@Override
public PropertySource<?> locate(Environment env) {
  ConfigService configService = nacosConfigProperties.configServiceInstance();
  if (null == configService) {
    log.warn("no instance of config service found, can't load config from nacos");
    return null;
  }
  long timeout = nacosConfigProperties.getTimeout();
  nacosPropertySourceBuilder = new NacosPropertySourceBuilder(configService,
      timeout);
  String name = nacosConfigProperties.getName();
  String nacosGroup = nacosConfigProperties.getGroup();
  String dataIdPrefix = nacosConfigProperties.getPrefix();
  if (StringUtils.isEmpty(dataIdPrefix)) {
    dataIdPrefix = name;
  }
  if (StringUtils.isEmpty(dataIdPrefix)) {
    dataIdPrefix = env.getProperty("spring.application.name");
  }
  List<String> profiles = Arrays.asList(env.getActiveProfiles());
  nacosConfigProperties.setActiveProfiles(profiles.toArray(new String[0]));
  String fileExtension = nacosConfigProperties.getFileExtension();
  CompositePropertySource composite = new CompositePropertySource(
      NACOS_PROPERTY_SOURCE_NAME);
  loadSharedConfiguration(composite);
  loadExtConfiguration(composite);
  loadApplicationConfiguration(composite, nacosGroup, dataIdPrefix, fileExtension);
  return composite;
}

代码示例来源:origin: spring-cloud/spring-cloud-sleuth

@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
    AnnotatedTypeMetadata md) {
  String sourceClass = "";
  if (md instanceof ClassMetadata) {
    sourceClass = ((ClassMetadata) md).getClassName();
  }
  ConditionMessage.Builder message = ConditionMessage.forCondition("ZipkinSender",
      sourceClass);
  String property = context.getEnvironment()
      .getProperty("spring.zipkin.sender.type");
  if (StringUtils.isEmpty(property)) {
    return ConditionOutcome.match(message.because("automatic sender type"));
  }
  String senderType = getType(((AnnotationMetadata) md).getClassName());
  if (property.equalsIgnoreCase(senderType)) {
    return ConditionOutcome.match(message.because(property + " sender type"));
  }
  return ConditionOutcome.noMatch(message.because(property + " sender type"));
}

代码示例来源:origin: sqshq/piggymetrics

@Override
  public void send(NotificationType type, Recipient recipient, String attachment) throws MessagingException, IOException {

    final String subject = env.getProperty(type.getSubject());
    final String text = MessageFormat.format(env.getProperty(type.getText()), recipient.getAccountName());

    MimeMessage message = mailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(recipient.getEmail());
    helper.setSubject(subject);
    helper.setText(text);

    if (StringUtils.hasLength(attachment)) {
      helper.addAttachment(env.getProperty(type.getAttachment()), new ByteArrayResource(attachment.getBytes()));
    }

    mailSender.send(message);

    log.info("{} email notification has been send to {}", type, recipient.getEmail());
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
  String location = element.getAttribute("location");
  if (StringUtils.hasLength(location)) {
    location = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(location);
    String[] locations = StringUtils.commaDelimitedListToStringArray(location);
    builder.addPropertyValue("locations", locations);
  }
  String propertiesRef = element.getAttribute("properties-ref");
  if (StringUtils.hasLength(propertiesRef)) {
    builder.addPropertyReference("properties", propertiesRef);
  }
  String fileEncoding = element.getAttribute("file-encoding");
  if (StringUtils.hasLength(fileEncoding)) {
    builder.addPropertyValue("fileEncoding", fileEncoding);
  }
  String order = element.getAttribute("order");
  if (StringUtils.hasLength(order)) {
    builder.addPropertyValue("order", Integer.valueOf(order));
  }
  builder.addPropertyValue("ignoreResourceNotFound",
      Boolean.valueOf(element.getAttribute("ignore-resource-not-found")));
  builder.addPropertyValue("localOverride",
      Boolean.valueOf(element.getAttribute("local-override")));
  builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
}

代码示例来源:origin: spring-projects/spring-framework

@Override
@Nullable
public BeanDefinition parse(Element element, ParserContext parserContext) {
  String basePackage = element.getAttribute(BASE_PACKAGE_ATTRIBUTE);
  basePackage = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(basePackage);
  String[] basePackages = StringUtils.tokenizeToStringArray(basePackage,
      ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
  // Actually scan for bean definitions and register them.
  ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element);
  Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages);
  registerComponents(parserContext.getReaderContext(), beanDefinitions, element);
  return null;
}

相关文章