当前位置: 首页>>代码示例>>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;未经允许,请勿转载。