Java 类org.springframework.core.env.ConfigurableEnvironment 实例源码

项目:multi-tenancy    文件:DefultProperties.java   
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));
    }
}
项目:iBase4J-Common    文件:Configs.java   
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);
    }
}
项目:iBase4J-Common    文件:Configs.java   
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();
}
项目:chimera    文件:SysDeployer.java   
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();
}
项目:micrometer    文件:MetricsEnvironmentPostProcessor.java   
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);
    }
}
项目:spring-cloud-discovery-version-filter    文件:PropertyTranslatorPostProcessor.java   
@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);
}
项目:azure-spring-boot    文件:VcapProcessor.java   
@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");
}
项目:hevelian-activemq    文件:WebXBeanBrokerFactory.java   
@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;
    }
}
项目:holon-core    文件:DefaultEnvironmentConfigPropertyProvider.java   
@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();
}
项目:loc-framework    文件:PrefixPropertyCondition.java   
@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));
}
项目:taboola-cronyx    文件:EnvironmentUtil.java   
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;
}
项目:zipkin-sparkstreaming    文件:ZipkinStorageConsumerAutoConfiguration.java   
@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");
  }
}
项目:smarti    文件:Application.java   
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());
    }
}
项目:java-demo    文件:Test.java   
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());
    }
项目:lodsve-framework    文件:ProfileInitializer.java   
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    ConfigurableEnvironment configEnv = applicationContext.getEnvironment();

    Configuration profileConfig = Env.getFrameworkEnv("profiles.properties");
    Set<String> profiles = profileConfig.subset("profiles").getKeys();

    if (CollectionUtils.isEmpty(profiles)) {
        return;
    }

    for (String profile : profiles) {
        if (profileConfig.getBoolean("profiles." + profile, false)) {
            configEnv.addActiveProfile(profile);
        }
    }
}
项目:oma-riista-web    文件:WebAppContextInitializer.java   
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    final ConfigurableEnvironment configurableEnvironment = applicationContext.getEnvironment();
    configurableEnvironment.setDefaultProfiles(Constants.STANDARD_DATABASE);

    final MutablePropertySources propertySources = configurableEnvironment.getPropertySources();

    AwsCloudRuntimeConfig.createPropertySource().ifPresent(awsPropertySource -> {
        propertySources.addLast(awsPropertySource);

        LOG.info("Using Amazon RDS profile");

        configurableEnvironment.setActiveProfiles(Constants.AMAZON_DATABASE);
    });

    LiquibaseConfig.replaceLiquibaseServiceLocator();
}
项目:spring-boot-concourse    文件:EndpointWebMvcAutoConfiguration.java   
@Override
public void afterSingletonsInstantiated() {
    ManagementServerPort managementPort = ManagementServerPort.DIFFERENT;
    if (this.applicationContext instanceof WebApplicationContext) {
        managementPort = ManagementServerPort
                .get(this.applicationContext.getEnvironment(), this.beanFactory);
    }
    if (managementPort == ManagementServerPort.DIFFERENT) {
        if (this.applicationContext instanceof EmbeddedWebApplicationContext
                && ((EmbeddedWebApplicationContext) this.applicationContext)
                        .getEmbeddedServletContainer() != null) {
            createChildManagementContext();
        }
        else {
            logger.warn("Could not start embedded management container on "
                    + "different port (management endpoints are still available "
                    + "through JMX)");
        }
    }
    if (managementPort == ManagementServerPort.SAME && this.applicationContext
            .getEnvironment() instanceof ConfigurableEnvironment) {
        addLocalManagementPortPropertyAlias(
                (ConfigurableEnvironment) this.applicationContext.getEnvironment());
    }
}
项目:spring-cloud-kubernetes    文件:KubernetesProfileApplicationListener.java   
void addKubernetesProfile(ConfigurableEnvironment environment) {
    Pod current = utils.currentPod().get();
    if (current != null) {
        if (!hasKubernetesProfile(environment)) {
            environment.addActiveProfile(KUBERNETES_PROFILE);
        }
    }

    if (utils.isInsideKubernetes()) {
        if (hasKubernetesProfile(environment)) {
            LOGGER.debug("'kubernetes' already in list of active profiles");
        } else {
            LOGGER.debug("Adding 'kubernetes' to list of active profiles");
            environment.addActiveProfile(KUBERNETES_PROFILE);
        }
    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.warn("Not running inside kubernetes. Skipping 'kuberntes' profile activation.");
        }
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:DevToolsHomePropertiesPostProcessor.java   
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
        SpringApplication application) {
    File home = getHomeFolder();
    File propertyFile = (home == null ? null : new File(home, FILE_NAME));
    if (propertyFile != null && propertyFile.exists() && propertyFile.isFile()) {
        FileSystemResource resource = new FileSystemResource(propertyFile);
        Properties properties;
        try {
            properties = PropertiesLoaderUtils.loadProperties(resource);
            environment.getPropertySources().addFirst(
                    new PropertiesPropertySource("devtools-local", properties));
        }
        catch (IOException ex) {
            throw new IllegalStateException("Unable to load " + FILE_NAME, ex);
        }
    }
}
项目:spring4-understanding    文件:DispatcherServletTests.java   
@Test
public void environmentOperations() {
    DispatcherServlet servlet = new DispatcherServlet();
    ConfigurableEnvironment defaultEnv = servlet.getEnvironment();
    assertThat(defaultEnv, notNullValue());
    ConfigurableEnvironment env1 = new StandardServletEnvironment();
    servlet.setEnvironment(env1); // should succeed
    assertThat(servlet.getEnvironment(), sameInstance(env1));
    try {
        servlet.setEnvironment(new DummyEnvironment());
        fail("expected IllegalArgumentException for non-configurable Environment");
    }
    catch (IllegalArgumentException ex) {
    }
    class CustomServletEnvironment extends StandardServletEnvironment { }
    @SuppressWarnings("serial")
    DispatcherServlet custom = new DispatcherServlet() {
        @Override
        protected ConfigurableWebEnvironment createEnvironment() {
            return new CustomServletEnvironment();
        }
    };
    assertThat(custom.getEnvironment(), instanceOf(CustomServletEnvironment.class));
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:SpringApplicationContextLoader.java   
@Override
public ApplicationContext loadContext(final MergedContextConfiguration config)
        throws Exception {
    assertValidAnnotations(config.getTestClass());
    SpringApplication application = getSpringApplication();
    application.setMainApplicationClass(config.getTestClass());
    application.setSources(getSources(config));
    ConfigurableEnvironment environment = new StandardEnvironment();
    if (!ObjectUtils.isEmpty(config.getActiveProfiles())) {
        setActiveProfiles(environment, config.getActiveProfiles());
    }
    Map<String, Object> properties = getEnvironmentProperties(config);
    addProperties(environment, properties);
    application.setEnvironment(environment);
    List<ApplicationContextInitializer<?>> initializers = getInitializers(config,
            application);
    if (config instanceof WebMergedContextConfiguration) {
        new WebConfigurer().configure(config, application, initializers);
    }
    else {
        application.setWebEnvironment(false);
    }
    application.setInitializers(initializers);
    ConfigurableApplicationContext applicationContext = application.run();
    return applicationContext;
}
项目:graviteeio-access-management    文件:SpringServletContext.java   
protected WebApplicationContext applicationContext() {
    if (applicationContext == null) {
        AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();

        Set<Class<?>> annotatedClasses = annotatedClasses();
        if (annotatedClasses != null) {
            annotatedClasses.iterator().forEachRemaining(webApplicationContext::register);
        }

        Set<? extends BeanFactoryPostProcessor> beanFactoryPostProcessors = beanFactoryPostProcessors();
        if (beanFactoryPostProcessors != null) {
            beanFactoryPostProcessors.iterator().forEachRemaining(webApplicationContext::addBeanFactoryPostProcessor);
        }

        if (this.rootApplicationContext != null) {
            webApplicationContext.setParent(this.rootApplicationContext);
            webApplicationContext.setEnvironment((ConfigurableEnvironment) rootApplicationContext.getEnvironment());
        }

        applicationContext = webApplicationContext;
    }

    return (WebApplicationContext) applicationContext;
}
项目:spring-boot-concourse    文件:SpringApplicationTests.java   
private Condition<ConfigurableEnvironment> matchingPropertySource(
        final Class<?> propertySourceClass, final String name) {
    return new Condition<ConfigurableEnvironment>("has property source") {

        @Override
        public boolean matches(ConfigurableEnvironment value) {
            for (PropertySource<?> source : value.getPropertySources()) {
                if (propertySourceClass.isInstance(source)
                        && (name == null || name.equals(source.getName()))) {
                    return true;
                }
            }
            return false;
        }

    };
}
项目:spring-boot-concourse    文件:RemoteUrlPropertyExtractor.java   
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    ConfigurableEnvironment environment = event.getEnvironment();
    String url = cleanRemoteUrl(environment.getProperty(NON_OPTION_ARGS));
    Assert.state(StringUtils.hasLength(url), "No remote URL specified");
    Assert.state(url.indexOf(",") == -1, "Multiple URLs specified");
    try {
        new URI(url);
    }
    catch (URISyntaxException ex) {
        throw new IllegalStateException("Malformed URL '" + url + "'");
    }
    Map<String, Object> source = Collections.singletonMap("remoteUrl", (Object) url);
    PropertySource<?> propertySource = new MapPropertySource("remoteUrl", source);
    environment.getPropertySources().addLast(propertySource);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:SpringApplication.java   
private Banner printBanner(ConfigurableEnvironment environment) {
    if (this.bannerMode == Banner.Mode.OFF) {
        return null;
    }
    if (printBannerViaDeprecatedMethod(environment)) {
        return null;
    }
    ResourceLoader resourceLoader = this.resourceLoader != null ? this.resourceLoader
            : new DefaultResourceLoader(getClassLoader());
    SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(
            resourceLoader, this.banner);
    if (this.bannerMode == Mode.LOG) {
        return bannerPrinter.print(environment, this.mainApplicationClass, logger);
    }
    return bannerPrinter.print(environment, this.mainApplicationClass, System.out);
}
项目:spring-vault    文件:VaultPropertySourceRegistrar.java   
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
        throws BeansException {

    ConfigurableEnvironment env = beanFactory.getBean(ConfigurableEnvironment.class);
    MutablePropertySources propertySources = env.getPropertySources();

    registerPropertySources(
            beanFactory.getBeansOfType(
                    org.springframework.vault.core.env.VaultPropertySource.class)
                    .values(), propertySources);

    registerPropertySources(
            beanFactory
                    .getBeansOfType(
                            org.springframework.vault.core.env.LeaseAwareVaultPropertySource.class)
                    .values(), propertySources);
}
项目:puzzle    文件:PluginSpringManager.java   
public void init(String location){
    applicationContext= new PluginXmlWebApplicationContext(pluginContext);
    applicationContext.setId(pluginContext.getName());
    applicationContext.setParent(WebApplicationContextUtils.getWebApplicationContext(PluginFramework.getFrameworkServletContext()));
    applicationContext.setServletContext(pluginContext.getServletContext());
    applicationContext.setServletConfig(pluginContext.getServletConfig());
    applicationContext.setClassLoader(pluginContext.getClassLoader());
    pluginContext.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext);
    applicationContext.setConfigLocation(location);
    ConfigurableEnvironment env = applicationContext.getEnvironment();
    if (env instanceof ConfigurableWebEnvironment) {
        ((ConfigurableWebEnvironment) env).initPropertySources(pluginContext.getServletContext(), null);
    }
    ((PluginContextSupport)pluginContext).setApplicationContext(applicationContext);
    try{
        applicationContext.refresh();  
    }catch(Throwable e){
        logger.error("Plugin ["+pluginContext.getName()+"] "+location+" parse failure",e);
        throw new PuzzleException(e);
    }
    registerPluginService2OSGiServiceBus();
    logger.info(location+" parse success");
}
项目:spring-boot-concourse    文件:DelegatingApplicationListener.java   
@SuppressWarnings("unchecked")
private List<ApplicationListener<ApplicationEvent>> getListeners(
        ConfigurableEnvironment env) {
    String classNames = env.getProperty(PROPERTY_NAME);
    List<ApplicationListener<ApplicationEvent>> listeners = new ArrayList<ApplicationListener<ApplicationEvent>>();
    if (StringUtils.hasLength(classNames)) {
        for (String className : StringUtils.commaDelimitedListToSet(classNames)) {
            try {
                Class<?> clazz = ClassUtils.forName(className,
                        ClassUtils.getDefaultClassLoader());
                Assert.isAssignable(ApplicationListener.class, clazz, "class ["
                        + className + "] must implement ApplicationListener");
                listeners.add((ApplicationListener<ApplicationEvent>) BeanUtils
                        .instantiateClass(clazz));
            }
            catch (Exception ex) {
                throw new ApplicationContextException(
                        "Failed to load context listener class [" + className + "]",
                        ex);
            }
        }
    }
    AnnotationAwareOrderComparator.sort(listeners);
    return listeners;
}
项目:camunda-bpm-cloud    文件:ConfigserverSpikeApplication.java   
private Map<String, Object> properties() {
  Map<String, Object> map = new HashMap();

  if (environment instanceof ConfigurableEnvironment) {
    for (PropertySource<?> propertySource : ((ConfigurableEnvironment) environment).getPropertySources()) {
      if (propertySource instanceof EnumerablePropertySource) {
        for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) {
          if (StringUtils.startsWithAny(key, "spring", "eureka", "camunda.bpm")) {
            map.put(key, propertySource.getProperty(key));
          }
        }
      }
    }
  }

  return map;
}
项目:spring-boot-concourse    文件:OnEnabledResourceChainCondition.java   
@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"));
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:DelegatingApplicationListener.java   
@SuppressWarnings("unchecked")
private List<ApplicationListener<ApplicationEvent>> getListeners(
        ConfigurableEnvironment env) {
    String classNames = env.getProperty(PROPERTY_NAME);
    List<ApplicationListener<ApplicationEvent>> listeners = new ArrayList<ApplicationListener<ApplicationEvent>>();
    if (StringUtils.hasLength(classNames)) {
        for (String className : StringUtils.commaDelimitedListToSet(classNames)) {
            try {
                Class<?> clazz = ClassUtils.forName(className,
                        ClassUtils.getDefaultClassLoader());
                Assert.isAssignable(ApplicationListener.class, clazz, "class ["
                        + className + "] must implement ApplicationListener");
                listeners.add((ApplicationListener<ApplicationEvent>) BeanUtils
                        .instantiateClass(clazz));
            }
            catch (Exception ex) {
                throw new ApplicationContextException(
                        "Failed to load context listener class [" + className + "]",
                        ex);
            }
        }
    }
    AnnotationAwareOrderComparator.sort(listeners);
    return listeners;
}
项目:spring-boot-concourse    文件:SpringApplication.java   
private Banner printBanner(ConfigurableEnvironment environment) {
    if (this.bannerMode == Banner.Mode.OFF) {
        return null;
    }
    if (printBannerViaDeprecatedMethod(environment)) {
        return null;
    }
    ResourceLoader resourceLoader = this.resourceLoader != null ? this.resourceLoader
            : new DefaultResourceLoader(getClassLoader());
    SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(
            resourceLoader, this.banner);
    if (this.bannerMode == Mode.LOG) {
        return bannerPrinter.print(environment, this.mainApplicationClass, logger);
    }
    return bannerPrinter.print(environment, this.mainApplicationClass, System.out);
}
项目:eds    文件:Application.java   
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    // 设置动态加载文件要使用的active.profile系统变量
    ConfigurableEnvironment env = event.getEnvironment();
    if(env != null){
        System.out.println("start eds Application , active profiles : "
                + Arrays.toString(env.getActiveProfiles()));
        String[] activeProfiles = env.getActiveProfiles();
        if(activeProfiles != null && activeProfiles.length > 0){
            String active = activeProfiles[0];
            System.setProperty("spring.profiles.active",active);
            System.out.println("eds system property [spring.profiles.active] variable : "+active);
        }
    }
}
项目:cas-5.1.0    文件:MongoDbPropertySourceLocator.java   
@Override
public PropertySource<?> locate(final Environment environment) {
    if (environment instanceof ConfigurableEnvironment) {
        final String sourceName = MongoDbPropertySource.class.getSimpleName();
        final CompositePropertySource composite = new CompositePropertySource(sourceName);
        final MongoDbPropertySource source = new MongoDbPropertySource(sourceName, mongo);
        composite.addFirstPropertySource(source);
        return composite;
    }
    return null;
}
项目:cas-5.1.0    文件:CasCoreUtilConfiguration.java   
@PostConstruct
public void init() {
    final ConfigurableApplicationContext ctx = applicationContextProvider().getConfigurableApplicationContext();
    final DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(true);
    conversionService.setEmbeddedValueResolver(new CasConfigurationEmbeddedValueResolver(ctx));
    ctx.getEnvironment().setConversionService(conversionService);
    final ConfigurableEnvironment env = (ConfigurableEnvironment) ctx.getParent().getEnvironment();
    env.setConversionService(conversionService);
    final ConverterRegistry registry = (ConverterRegistry) DefaultConversionService.getSharedInstance();
    registry.addConverter(zonedDateTimeToStringConverter());
}
项目:configx    文件:MultiVersionPropertySourceFactory.java   
/**
 * 返回Environment中的多版本属性源,不存在则创建
 *
 * @param environment
 * @return
 */
public static MultiVersionPropertySource getMultiVersionPropertySource(ConfigurableEnvironment environment) {
    PropertySource<?> multiVersionPropertySource = environment.getPropertySources().get(MULTIVERSION_PROPERTY_SOURCE_NAME);

    // 不存在多版本属性源,则创建
    if (multiVersionPropertySource == null) {
        multiVersionPropertySource = createMultiVersionPropertySource();
        environment.getPropertySources().addLast(multiVersionPropertySource);
    }

    return (MultiVersionPropertySource) multiVersionPropertySource;
}
项目:configx    文件:MultiVersionPropertySourceFactory.java   
/**
 * 向Environment中添加版本属性源
 *
 * @param versionPropertySource
 * @param applicationContext
 * @param environment
 */
public static void addVersionPropertySource(VersionPropertySource<ConfigItemList> versionPropertySource,
                                            ApplicationContext applicationContext,
                                            ConfigurableEnvironment environment) {
    if (versionPropertySource == null) {
        return;
    }

    MultiVersionPropertySource multiVersionPropertySource = getMultiVersionPropertySource(environment);
    multiVersionPropertySource.addPropertySource(versionPropertySource);
}
项目:micrometer    文件:MetricsEnvironmentPostProcessor.java   
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
                                   SpringApplication application) {
    // Make spring AOP default to target class so RestTemplates can be customized,
    // @Scheduled instrumented
    log.debug("Setting 'spring.aop.proxyTargetClass=true' to make spring AOP default to target class so RestTemplates can be customized");
    addDefaultProperty(environment, "spring.aop.proxyTargetClass", "true");
}
项目:spring-cloud-dataflow-metrics-collector    文件:ApplicationMetricsBindingPostProcessor.java   
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    Map<String, Object> propertiesToAdd = new HashMap<>();
    propertiesToAdd.put("spring.cloud.stream.bindings.input.destination", "metrics");
    propertiesToAdd.put("spring.jackson.default-property-inclusion", "non_null");
    environment.getPropertySources().addLast(new MapPropertySource("collectorDefaultProperties", propertiesToAdd));
}
项目:spring-cloud-discovery-version-filter    文件:PropertyTranslatorPostProcessor.java   
private MapPropertySource findZuulPropertySource(ConfigurableEnvironment environment) {
  for (PropertySource<?> propertySource : environment.getPropertySources()) {
    if (propertySource instanceof MapPropertySource) {
      for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) {
        if (key.toLowerCase().startsWith(ZUUL_SERVICE_VERSIONS_ROOT)) {
          return (MapPropertySource) propertySource;
        }
      }
    }
  }
  return null;
}