當前位置: 首頁>>代碼示例>>Java>>正文


Java ConfigurableEnvironment類代碼示例

本文整理匯總了Java中org.springframework.core.env.ConfigurableEnvironment的典型用法代碼示例。如果您正苦於以下問題:Java ConfigurableEnvironment類的具體用法?Java ConfigurableEnvironment怎麽用?Java ConfigurableEnvironment使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ConfigurableEnvironment類屬於org.springframework.core.env包,在下文中一共展示了ConfigurableEnvironment類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: onApplicationEvent

import org.springframework.core.env.ConfigurableEnvironment; //導入依賴的package包/類
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    ConfigurableEnvironment environment = event.getEnvironment();
    configurableEnvironment=environment;
    Properties props = new Properties();

    String databaseMode = environment.getProperty("me.ramon.database-mode");

    if (databaseMode != null) {
        if (databaseMode.equals("hibernate-multitenant")) {
            props.put("spring.jpa.properties.hibernate.multiTenancy", "DATABASE");
            props.put("spring.jpa.properties.hibernate.tenant_identifier_resolver", "me.ramon.multitenancy.BaseCurrentTenantIdentifierResolverImp");
            props.put("spring.jpa.properties.hibernate.multi_tenant_connection_provider", "me.ramon.multitenancy.BaseMultiTenantConnectionProviderImp");
        }
        props.put("spring.jpa.hibernate.ddl-auto", "none");
        props.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        props.put("hibernate.show_sql", "true");
        props.put("logging.level.org.hibernate.SQL", "DEBUG");
        props.put("logging.level.org.hibernate.type.descriptor.sql.BasicBinder", "TRACE");
        props.put("spring.jpa.properties.hibernate.current_session_context_class", "org.springframework.orm.hibernate4.SpringSessionContext");
        environment.getPropertySources().addLast(new PropertiesPropertySource("application1", props));
    }
}
 
開發者ID:mojtaba-sharif,項目名稱:multi-tenancy,代碼行數:23,代碼來源:DefultProperties.java

示例2: getMatchOutcome

import org.springframework.core.env.ConfigurableEnvironment; //導入依賴的package包/類
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
		AnnotatedTypeMetadata metadata) {
	ConfigurableEnvironment environment = (ConfigurableEnvironment) context
			.getEnvironment();
	ResourceProperties properties = new ResourceProperties();
	RelaxedDataBinder binder = new RelaxedDataBinder(properties, "spring.resources");
	binder.bind(new PropertySourcesPropertyValues(environment.getPropertySources()));
	Boolean match = properties.getChain().getEnabled();
	if (match == null) {
		boolean webJarsLocatorPresent = ClassUtils.isPresent(WEBJAR_ASSERT_LOCATOR,
				getClass().getClassLoader());
		return new ConditionOutcome(webJarsLocatorPresent,
				"Webjars locator (" + WEBJAR_ASSERT_LOCATOR + ") is "
						+ (webJarsLocatorPresent ? "present" : "absent"));
	}
	return new ConditionOutcome(match,
			"Resource chain is " + (match ? "enabled" : "disabled"));
}
 
開發者ID:philwebb,項目名稱:spring-boot-concourse,代碼行數:20,代碼來源:OnEnabledResourceChainCondition.java

示例3: postProcessEnvironment

import org.springframework.core.env.ConfigurableEnvironment; //導入依賴的package包/類
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    // 此處可以http方式 到配置服務器拉取一堆公共配置+本項目個性配置的json串,拚到Properties裏
    // ......省略new Properties的過程
    MutablePropertySources propertySources = environment.getPropertySources();
    // addLast 結合下麵的 getOrder() 保證順序 讀者也可以試試其他姿勢的加載順序
    try {
        Properties props = getConfig(environment);
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            String value = props.getProperty(keyStr);
            if ("druid.writer.password,druid.reader.password".contains(keyStr)) {
                String dkey = props.getProperty("druid.key");
                dkey = DataUtil.isEmpty(dkey) ? Constants.DB_KEY : dkey;
                value = SecurityUtil.decryptDes(value, dkey.getBytes());
                props.setProperty(keyStr, value);
            }
            PropertiesUtil.getProperties().put(keyStr, value);
        }
        propertySources.addLast(new PropertiesPropertySource("thirdEnv", props));
    } catch (IOException e) {
        logger.error("", e);
    }
}
 
開發者ID:iBase4J,項目名稱:iBase4J-Common,代碼行數:24,代碼來源:Configs.java

示例4: getConfig

import org.springframework.core.env.ConfigurableEnvironment; //導入依賴的package包/類
public Properties getConfig(ConfigurableEnvironment env) throws IOException {
    PropertiesFactoryBean config = new PropertiesFactoryBean();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    List<Resource> resouceList = InstanceUtil.newArrayList();
    try {
        Resource[] resources = resolver.getResources("classpath*:config/*.properties");
        for (Resource resource : resources) {
            resouceList.add(resource);
        }
    } catch (Exception e) {
        logger.error("", e);
    }
    config.setLocations(resouceList.toArray(new Resource[]{}));
    config.afterPropertiesSet();
    return config.getObject();
}
 
開發者ID:iBase4J,項目名稱:iBase4J-Common,代碼行數:17,代碼來源:Configs.java

示例5: start

import org.springframework.core.env.ConfigurableEnvironment; //導入依賴的package包/類
public void start() throws Exception
{
    ConfigurableEnvironment ce = (ConfigurableEnvironment) applicationContext.getEnvironment();
    RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    String jvmName = runtimeBean.getName();
    long pid = Long.valueOf(jvmName.split("@")[0]);

    final File tmpDir = new File(".", ".tmp_" + pid);
    if (tmpDir.exists())
    {
        deleteRecursive(tmpDir);
    }

    //noinspection ResultOfMethodCallIgnored
    tmpDir.mkdir();

    Runtime.getRuntime().addShutdownHook(new Thread(this::stop));

    baseDir = tmpDir.getAbsolutePath();
    PropertyResolver resolver = new SpringPropertyResolver(ce);
    resolver.initialize();

    deployer = ResourceDeployer.newInstance(resolver, tmpDir);
    deployer.installRuntimeResources();
    deployer.startConfigMonitoring();
}
 
開發者ID:vmantek,項目名稱:chimera,代碼行數:27,代碼來源:SysDeployer.java

示例6: addDefaultProperty

import org.springframework.core.env.ConfigurableEnvironment; //導入依賴的package包/類
private void addDefaultProperty(ConfigurableEnvironment environment, String name,
                                String value) {
    MutablePropertySources sources = environment.getPropertySources();
    Map<String, Object> map = null;
    if (sources.contains("defaultProperties")) {
        PropertySource<?> source = sources.get("defaultProperties");
        if (source instanceof MapPropertySource) {
            map = ((MapPropertySource) source).getSource();
        }
    } else {
        map = new LinkedHashMap<>();
        sources.addLast(new MapPropertySource("defaultProperties", map));
    }
    if (map != null) {
        map.put(name, value);
    }
}
 
開發者ID:micrometer-metrics,項目名稱:micrometer,代碼行數:18,代碼來源:MetricsEnvironmentPostProcessor.java

示例7: translateZuulRoutes

import org.springframework.core.env.ConfigurableEnvironment; //導入依賴的package包/類
@SuppressWarnings("unchecked")
private void translateZuulRoutes(ConfigurableEnvironment environment) {

  //TODO should be fixed to multiple propertySource usage
  MapPropertySource zuulSource = findZuulPropertySource(environment);
  if (zuulSource == null) {
    return;
  }

  Map<String, String> customServiceVersions = new HashMap<>();
  for (String name : zuulSource.getPropertyNames()) {
    extractServiceVersion(zuulSource, name, customServiceVersions);
  }

  Map<String, Object> properties = new HashMap<>();
  properties.put(CUSTOM_SERVICE_VERSIONS_PROP, customServiceVersions);
  MapPropertySource target = new MapPropertySource(ZUUL_PROPERTY_SOURCE_NAME, properties);
  environment.getPropertySources().addFirst(target);
}
 
開發者ID:gorelikov,項目名稱:spring-cloud-discovery-version-filter,代碼行數:20,代碼來源:PropertyTranslatorPostProcessor.java

示例8: postProcessEnvironment

import org.springframework.core.env.ConfigurableEnvironment; //導入依賴的package包/類
@Override
public void postProcessEnvironment(ConfigurableEnvironment confEnv,
                                   SpringApplication app) {
    final Map<String, Object> environment = confEnv.getSystemEnvironment();

    final String logValue = (String) environment.get(VcapProcessor.LOG_VARIABLE);
    if ("true".equals(logValue)) {
        logFlag = true;
    }

    log("VcapParser.postProcessEnvironment: Start");
    final String vcapServices = (String) environment
            .get(VcapProcessor.VCAP_SERVICES);
    final VcapResult result = parse(vcapServices);
    result.setLogFlag(logFlag);
    result.setConfEnv(confEnv);
    result.populateProperties();
    log("VcapParser.postProcessEnvironment: End");
}
 
開發者ID:Microsoft,項目名稱:azure-spring-boot,代碼行數:20,代碼來源:VcapProcessor.java

示例9: createApplicationContext

import org.springframework.core.env.ConfigurableEnvironment; //導入依賴的package包/類
@Override
protected ApplicationContext createApplicationContext(String uri) throws MalformedURLException {
	Resource resource = Utils.resourceFromString(uri);
	LOG.debug("Using " + resource + " from " + uri);
	try {
		return new ResourceXmlApplicationContext(resource) {
			@Override
			protected ConfigurableEnvironment createEnvironment() {
				return new ReversePropertySourcesStandardServletEnvironment();
			}

			@Override
			protected void initPropertySources() {
				WebApplicationContextUtils.initServletPropertySources(getEnvironment().getPropertySources(),
						ServletContextHolder.getServletContext());
			}
		};
	} catch (FatalBeanException errorToLog) {
		LOG.error("Failed to load: " + resource + ", reason: " + errorToLog.getLocalizedMessage(), errorToLog);
		throw errorToLog;
	}
}
 
開發者ID:Hevelian,項目名稱:hevelian-activemq,代碼行數:23,代碼來源:WebXBeanBrokerFactory.java

示例10: getPropertyNames

import org.springframework.core.env.ConfigurableEnvironment; //導入依賴的package包/類
@Override
public Stream<String> getPropertyNames() throws UnsupportedOperationException {
	List<String> names = new LinkedList<>();
	if (ConfigurableEnvironment.class.isAssignableFrom(getEnvironment().getClass())) {
		MutablePropertySources propertySources = ((ConfigurableEnvironment) getEnvironment()).getPropertySources();
		if (propertySources != null) {
			Iterator<PropertySource<?>> i = propertySources.iterator();
			while (i.hasNext()) {
				PropertySource<?> source = i.next();
				if (source instanceof EnumerablePropertySource) {
					String[] propertyNames = ((EnumerablePropertySource<?>) source).getPropertyNames();
					if (propertyNames != null) {
						names.addAll(Arrays.asList(propertyNames));
					}
				}
			}
		}
	}
	return names.stream();
}
 
開發者ID:holon-platform,項目名稱:holon-core,代碼行數:21,代碼來源:DefaultEnvironmentConfigPropertyProvider.java

示例11: getMatchOutcome

import org.springframework.core.env.ConfigurableEnvironment; //導入依賴的package包/類
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
    AnnotatedTypeMetadata metadata) {
  String prefix = (String) attribute(metadata, "prefix");
  Class<?> value = (Class<?>) attribute(metadata, "value");
  ConfigurableEnvironment environment = (ConfigurableEnvironment) context.getEnvironment();
  try {
    new Binder(ConfigurationPropertySources.from(environment.getPropertySources()))
        .bind(prefix, Bindable.of(value))
        .orElseThrow(
            () -> new FatalBeanException("Could not bind DataSourceSettings properties"));
    return new ConditionOutcome(true, String.format("Map property [%s] is not empty", prefix));
  } catch (Exception e) {
    //ignore
  }
  return new ConditionOutcome(false, String.format("Map property [%s] is empty", prefix));
}
 
開發者ID:lord-of-code,項目名稱:loc-framework,代碼行數:18,代碼來源:PrefixPropertyCondition.java

示例12: findProps

import org.springframework.core.env.ConfigurableEnvironment; //導入依賴的package包/類
public static Properties findProps(ConfigurableEnvironment env, String prefix){
    Properties props = new Properties();

    for (PropertySource<?> source : env.getPropertySources()) {
        if (source instanceof EnumerablePropertySource) {
            EnumerablePropertySource<?> enumerable = (EnumerablePropertySource<?>) source;
            for (String name : enumerable.getPropertyNames()) {
                if (name.startsWith(prefix)) {
                    props.putIfAbsent(name, enumerable.getProperty(name));
                }
            }

        }
    }

    return props;
}
 
開發者ID:taboola,項目名稱:taboola-cronyx,代碼行數:18,代碼來源:EnvironmentUtil.java

示例13: storageConsumer

import org.springframework.core.env.ConfigurableEnvironment; //導入依賴的package包/類
@ConditionalOnBean(StorageComponent.class)
@Bean StorageConsumer storageConsumer(
    StorageComponent component,
    @Value("${zipkin.sparkstreaming.consumer.storage.fail-fast:true}") boolean failFast,
    BeanFactory bf
) throws IOException {
  if (failFast) checkStorageOk(component);
  Properties properties = extractZipkinProperties(bf.getBean(ConfigurableEnvironment.class));
  if (component instanceof V2StorageComponent) {
    zipkin2.storage.StorageComponent v2Storage = ((V2StorageComponent) component).delegate();
    if (v2Storage instanceof ElasticsearchHttpStorage) {
      return new ElasticsearchStorageConsumer(properties);
    } else if (v2Storage instanceof zipkin2.storage.cassandra.CassandraStorage) {
      return new Cassandra3StorageConsumer(properties);
    } else {
      throw new UnsupportedOperationException(v2Storage + " not yet supported");
    }
  } else if (component instanceof CassandraStorage) {
    return new CassandraStorageConsumer(properties);
  } else if (component instanceof MySQLStorage) {
    return new MySQLStorageConsumer(properties);
  } else {
    throw new UnsupportedOperationException(component + " not yet supported");
  }
}
 
開發者ID:openzipkin,項目名稱:zipkin-sparkstreaming,代碼行數:26,代碼來源:ZipkinStorageConsumerAutoConfiguration.java

示例14: main

import org.springframework.core.env.ConfigurableEnvironment; //導入依賴的package包/類
public static void main(String[] args) {
    final SpringApplication app = new SpringApplication(Application.class);
    // save the pid into a file...
    app.addListeners(new ApplicationPidFileWriter("smarti.pid"));

    final ConfigurableApplicationContext context = app.run(args);
    final ConfigurableEnvironment env = context.getEnvironment();

    try {
        //http://localhost:8080/admin/index.html
        final URI uri = new URI(
                (env.getProperty("server.ssl.enabled", Boolean.class, false) ? "https" : "http"),
                null,
                (env.getProperty("server.address", "localhost")),
                (env.getProperty("server.port", Integer.class, 8080)),
                (env.getProperty("server.context-path", "/")).replaceAll("//+", "/"),
                null, null);

        log.info("{} started: {}",
                env.getProperty("server.display-name", context.getDisplayName()),
                uri);
    } catch (URISyntaxException e) {
        log.warn("Could not build launch-url: {}", e.getMessage());
    }
}
 
開發者ID:redlink-gmbh,項目名稱:smarti,代碼行數:26,代碼來源:Application.java

示例15: main

import org.springframework.core.env.ConfigurableEnvironment; //導入依賴的package包/類
public static void main(String[] args) {
//        ApplicationContext context = new AnnotationConfigApplicationContext("com");
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(Config.class);
//        context.getEnvironment().addActiveProfile("dev");
        ConfigurableEnvironment environment = context.getEnvironment();
        environment.setDefaultProfiles("dev");
        environment.setActiveProfiles("prod");
        context.refresh();

        Student student = (Student) context.getBean("student");
        Student SpELStudent = (Student) context.getBean("SpELStudent");
        Teacher teacher = (Teacher) context.getBean("teacher");
        System.out.println(student);
        System.out.println(SpELStudent);
        System.out.println(teacher);
        System.out.println(teacher.getPen());

        teacher.teach("Math");
        System.out.println(teacher.getPenColor());
    }
 
開發者ID:Ulyssesss,項目名稱:java-demo,代碼行數:22,代碼來源:Test.java


注:本文中的org.springframework.core.env.ConfigurableEnvironment類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。