org.springframework.core.env.Environment Java Examples
The following examples show how to use
org.springframework.core.env.Environment.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BootstrapConfigurationTests.java From spring-cloud-commons with Apache License 2.0 | 6 votes |
@Override public PropertySource<?> locate(Environment environment) { if (this.name != null) { then(this.name) .isEqualTo(environment.getProperty("spring.application.name")); } if (this.fail) { throw new RuntimeException("Planned"); } CompositePropertySource compositePropertySource = new CompositePropertySource( "listTestBootstrap"); compositePropertySource.addFirstPropertySource( new MapPropertySource("testBootstrap1", MAP1)); compositePropertySource.addFirstPropertySource( new MapPropertySource("testBootstrap2", MAP2)); return compositePropertySource; }
Example #2
Source File: LogbackIntegrationTest.java From sofa-common-tools with Apache License 2.0 | 6 votes |
/** * test logging.config.{space id} config * @throws IOException */ @Test public void testLogConfig() throws IOException { Map<String, Object> properties = new HashMap<String, Object>(); properties.put(Constants.LOG_CONFIG_PREFIX + TEST_SPACE, "logback-test-conf.xml"); SpringApplication springApplication = new SpringApplication(EmptyConfig.class); springApplication.setDefaultProperties(properties); ConfigurableApplicationContext applicationContext = springApplication.run(new String[] {}); Environment environment = applicationContext.getEnvironment(); File logFile = getLogbackDefaultFile(environment); FileUtils.write(logFile, StringUtil.EMPTY_STRING, environment.getProperty(Constants.LOG_ENCODING_PROP_KEY)); logger.info("info level"); List<String> contents = FileUtils.readLines(logFile, environment.getProperty(Constants.LOG_ENCODING_PROP_KEY)); Assert.assertEquals(1, contents.size()); Assert.assertTrue(contents.get(0).contains("logback-test-conf")); LogEnvUtils.processGlobalSystemLogProperties().remove( Constants.LOG_CONFIG_PREFIX + TEST_SPACE); }
Example #3
Source File: WebSecurityConfig.java From alf.io with GNU General Public License v3.0 | 6 votes |
public OpenIdFormBasedWebSecurity(Environment environment, UserManager userManager, RecaptchaService recaptchaService, ConfigurationManager configurationManager, CsrfTokenRepository csrfTokenRepository, DataSource dataSource, PasswordEncoder passwordEncoder, OpenIdAuthenticationManager openIdAuthenticationManager, UserRepository userRepository, AuthorityRepository authorityRepository, UserOrganizationRepository userOrganizationRepository, OrganizationRepository organizationRepository) { super(environment, userManager, recaptchaService, configurationManager, csrfTokenRepository, dataSource, passwordEncoder, openIdAuthenticationManager, userRepository, authorityRepository, userOrganizationRepository, organizationRepository); }
Example #4
Source File: BaeldungApp.java From tutorials with MIT License | 6 votes |
/** * Main method, used to run the application. * * @param args the command line arguments * @throws UnknownHostException if the local host name could not be resolved into an address */ public static void main(String[] args) throws UnknownHostException { SpringApplication app = new SpringApplication(BaeldungApp.class); DefaultProfileUtil.addDefaultProfile(app); Environment env = app.run(args).getEnvironment(); String protocol = "http"; if (env.getProperty("server.ssl.key-store") != null) { protocol = "https"; } log.info("\n----------------------------------------------------------\n\t" + "Application '{}' is running! Access URLs:\n\t" + "Local: \t\t{}://localhost:{}\n\t" + "External: \t{}://{}:{}\n\t" + "Profile(s): \t{}\n----------------------------------------------------------", env.getProperty("spring.application.name"), protocol, env.getProperty("server.port"), protocol, InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port"), env.getActiveProfiles()); }
Example #5
Source File: GoogleConfigPropertySourceLocator.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@Override public PropertySource<?> locate(Environment environment) { if (!this.enabled) { return new MapPropertySource(PROPERTY_SOURCE_NAME, Collections.emptyMap()); } Map<String, Object> config; try { GoogleConfigEnvironment googleConfigEnvironment = getRemoteEnvironment(); Assert.notNull(googleConfigEnvironment, "Configuration not in expected format."); config = googleConfigEnvironment.getConfig(); } catch (Exception ex) { String message = String.format("Error loading configuration for %s/%s_%s", this.projectId, this.name, this.profile); throw new RuntimeException(message, ex); } return new MapPropertySource(PROPERTY_SOURCE_NAME, config); }
Example #6
Source File: AlertStartupInitializerTest.java From blackduck-alert with Apache License 2.0 | 6 votes |
@Test public void testInitializeConfigs() throws Exception { Environment environment = Mockito.mock(Environment.class); DescriptorAccessor baseDescriptorAccessor = Mockito.mock(DescriptorAccessor.class); ConfigurationAccessor baseConfigurationAccessor = Mockito.mock(ConfigurationAccessor.class); EncryptionUtility encryptionUtility = Mockito.mock(EncryptionUtility.class); Mockito.when(encryptionUtility.isInitialized()).thenReturn(Boolean.TRUE); EncryptionSettingsValidator encryptionValidator = new EncryptionSettingsValidator(encryptionUtility); ChannelDescriptor channelDescriptor = new EmailDescriptor(EMAIL_CHANNEL_KEY, new EmailGlobalUIConfig(encryptionValidator), null); List<DescriptorKey> descriptorKeys = List.of(channelDescriptor.getDescriptorKey()); List<ChannelDescriptor> channelDescriptors = List.of(channelDescriptor); List<ProviderDescriptor> providerDescriptors = List.of(); List<ComponentDescriptor> componentDescriptors = List.of(); EnvironmentVariableUtility environmentVariableUtility = new EnvironmentVariableUtility(environment); DescriptorMap descriptorMap = new DescriptorMap(descriptorKeys, channelDescriptors, providerDescriptors, componentDescriptors); ConfigurationFieldModelConverter modelConverter = new ConfigurationFieldModelConverter(encryptionUtility, baseDescriptorAccessor, descriptorMap); Mockito.when(baseDescriptorAccessor.getFieldsForDescriptor(Mockito.any(DescriptorKey.class), Mockito.any(ConfigContextEnum.class))).thenReturn(List.copyOf(channelDescriptor.getAllDefinedFields(ConfigContextEnum.GLOBAL))); FieldModelProcessor fieldModelProcessor = new FieldModelProcessor(modelConverter, new FieldValidationAction(), new DescriptorProcessor(descriptorMap, baseConfigurationAccessor, List.of(), List.of())); SettingsUtility settingsUtility = Mockito.mock(SettingsUtility.class); Mockito.when(settingsUtility.getKey()).thenReturn(new SettingsDescriptorKey()); AlertStartupInitializer initializer = new AlertStartupInitializer(descriptorMap, environmentVariableUtility, baseDescriptorAccessor, baseConfigurationAccessor, modelConverter, fieldModelProcessor, settingsUtility); initializer.initializeComponent(); Mockito.verify(baseDescriptorAccessor, Mockito.times(3)).getFieldsForDescriptor(Mockito.any(DescriptorKey.class), Mockito.any(ConfigContextEnum.class)); Mockito.verify(baseConfigurationAccessor, Mockito.times(2)).getConfigurationsByDescriptorKeyAndContext(Mockito.any(DescriptorKey.class), Mockito.any(ConfigContextEnum.class)); }
Example #7
Source File: ZookeeperLoadBalancerConfiguration.java From spring-cloud-zookeeper with Apache License 2.0 | 6 votes |
@Bean @ConditionalOnBean(DiscoveryClient.class) @ConditionalOnMissingBean public ServiceInstanceListSupplier zookeeperDiscoveryClientServiceInstanceListSupplier( DiscoveryClient discoveryClient, Environment env, ApplicationContext context, ZookeeperDependencies zookeeperDependencies) { DiscoveryClientServiceInstanceListSupplier firstDelegate = new DiscoveryClientServiceInstanceListSupplier( discoveryClient, env); ZookeeperServiceInstanceListSupplier secondDelegate = new ZookeeperServiceInstanceListSupplier(firstDelegate, zookeeperDependencies); ObjectProvider<LoadBalancerCacheManager> cacheManagerProvider = context .getBeanProvider(LoadBalancerCacheManager.class); if (cacheManagerProvider.getIfAvailable() != null) { return new CachingServiceInstanceListSupplier(secondDelegate, cacheManagerProvider.getIfAvailable()); } return secondDelegate; }
Example #8
Source File: UrlJarLoader.java From alchemy with Apache License 2.0 | 5 votes |
public UrlJarLoader(Environment env) { if (env == null) { //just for test this.properties = createProperties("META-INF/alchemy-dev.properties"); } else { if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) { this.properties = createProperties("META-INF/alchemy-dev.properties"); } else { this.properties = createProperties("META-INF/alchemy.properties"); } } }
Example #9
Source File: StartEventListener.java From blade-tool with GNU Lesser General Public License v3.0 | 5 votes |
@Async @Order @EventListener(WebServerInitializedEvent.class) public void afterStart(WebServerInitializedEvent event) { Environment environment = event.getApplicationContext().getEnvironment(); String appName = environment.getProperty("spring.application.name").toUpperCase(); int localPort = event.getWebServer().getPort(); String profile = StringUtils.arrayToCommaDelimitedString(environment.getActiveProfiles()); log.info("---[{}]---启动完成,当前使用的端口:[{}],环境变量:[{}]---", appName, localPort, profile); }
Example #10
Source File: ConsulAutoRegistration.java From spring-cloud-consul with Apache License 2.0 | 5 votes |
/** * @param properties consul discovery properties * @param env Spring environment * @return the app name, currently the spring.application.name property */ public static String getAppName(ConsulDiscoveryProperties properties, Environment env) { final String appName = properties.getServiceName(); if (StringUtils.hasText(appName)) { return appName; } return env.getProperty("spring.application.name", "application"); }
Example #11
Source File: HashPartitionStrategyCrutch.java From nakadi with MIT License | 5 votes |
@Autowired @SuppressWarnings("unchecked") public HashPartitionStrategyCrutch(final Environment environment, @Value("${" + PROPERTY_PREFIX + ".max:0}") final int maxPartitionNum) { final ImmutableMap.Builder<Integer, List<Integer>> mapBuilder = ImmutableMap.builder(); for (int pCount = 1; pCount <= maxPartitionNum; pCount++) { final String propertyName = PROPERTY_PREFIX + ".p" + pCount; final List<String> predefinedOrder = (List<String>) environment.getProperty(propertyName, List.class); if (predefinedOrder != null) { final List<Integer> predefinedOrderInt = predefinedOrder.stream() .map(Integer::parseInt) .collect(Collectors.toList()); // check that element count equals to number of partitions if (pCount != predefinedOrder.size()) { throw new IllegalArgumentException(propertyName + " property has wrong count of elements"); } // check that there is not index that is out of bounds final int partitionMaxIndex = pCount - 1; final boolean indexOutOfBouns = predefinedOrderInt.stream() .anyMatch(index -> index > partitionMaxIndex || index < 0); if (indexOutOfBouns) { throw new IllegalArgumentException(propertyName + " property has wrong partition index"); } mapBuilder.put(pCount, predefinedOrderInt); } } partitionsOrder = mapBuilder.build(); LOG.info("Initialized partitions override map with {} values:", partitionsOrder.size()); partitionsOrder.forEach((partitionCount, order) -> LOG.info("{}: {}", partitionCount, order)); }
Example #12
Source File: WebAnnoBanner.java From webanno with Apache License 2.0 | 5 votes |
@Override public void printBanner(Environment environment, Class<?> sourceClass, PrintStream printStream) { for (String line : BANNER) { printStream.println(line); } String version = SettingsUtil.getVersionString(); printStream.println(AnsiOutput.toString(AnsiColor.GREEN, AnsiStyle.FAINT, version)); printStream.println(); }
Example #13
Source File: DubboRegistryZooKeeperProviderBootstrap.java From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
public static void main(String[] args) { new SpringApplicationBuilder(DubboRegistryZooKeeperProviderBootstrap.class) .listeners((ApplicationListener<ApplicationEnvironmentPreparedEvent>) event -> { Environment environment = event.getEnvironment(); int port = environment.getProperty("embedded.zookeeper.port", int.class); new EmbeddedZooKeeper(port, false).start(); }) .run(args); }
Example #14
Source File: DefaultLazyPropertyResolver.java From jasypt-spring-boot with MIT License | 5 votes |
public DefaultLazyPropertyResolver(EncryptablePropertyDetector propertyDetector, StringEncryptor encryptor, String customResolverBeanName, boolean isCustom, BeanFactory bf, Environment environment) { singleton = new Singleton<>(() -> Optional.of(customResolverBeanName) .filter(bf::containsBean) .map(name -> (EncryptablePropertyResolver) bf.getBean(name)) .map(tap(bean -> log.info("Found Custom Resolver Bean {} with name: {}", bean, customResolverBeanName))) .orElseGet(() -> { if (isCustom) { throw new IllegalStateException(String.format("Property Resolver custom Bean not found with name '%s'", customResolverBeanName)); } log.info("Property Resolver custom Bean not found with name '{}'. Initializing Default Property Resolver", customResolverBeanName); return createDefault(propertyDetector, encryptor, environment); })); }
Example #15
Source File: ServiceAApplication.java From spring-cloud-gray with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws UnknownHostException { Environment env = new SpringApplicationBuilder(ServiceAApplication.class).web(true).run(args).getEnvironment(); log.info( "\n----------------------------------------------------------\n\t" + "Application '{}' is running! Access URLs:\n\t" + "Local: \t\thttp://127.0.0.1:{}\n\t" + "External: \thttp://{}:{}\n----------------------------------------------------------", env.getProperty("spring.application.name"), env.getProperty("server.port"), InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port")); String configServerStatus = env.getProperty("configserver.status"); log.info( "\n----------------------------------------------------------\n\t" + "Config Server: \t{}\n----------------------------------------------------------", configServerStatus == null ? "Not found or not setup for this application" : configServerStatus); }
Example #16
Source File: StartedUpRunner.java From FEBS-Cloud with Apache License 2.0 | 5 votes |
private static void printSystemUpBanner(Environment environment) { String banner = "-----------------------------------------\n" + "服务启动成功,时间:" + LocalDateTime.now() + "\n" + "服务名称:" + environment.getProperty("spring.application.name") + "\n" + "端口号:" + environment.getProperty("server.port") + "\n" + "-----------------------------------------"; System.out.println(banner); }
Example #17
Source File: AbstractApplicationContext.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} * <p>The parent {@linkplain ApplicationContext#getEnvironment() environment} is * {@linkplain ConfigurableEnvironment#merge(ConfigurableEnvironment) merged} with * this (child) application context environment if the parent is non-{@code null} and * its environment is an instance of {@link ConfigurableEnvironment}. * @see ConfigurableEnvironment#merge(ConfigurableEnvironment) */ @Override public void setParent(ApplicationContext parent) { this.parent = parent; if (parent != null) { Environment parentEnvironment = parent.getEnvironment(); if (parentEnvironment instanceof ConfigurableEnvironment) { getEnvironment().merge((ConfigurableEnvironment) parentEnvironment); } } }
Example #18
Source File: ConfigClientProperties.java From spring-cloud-config with Apache License 2.0 | 5 votes |
public ConfigClientProperties(Environment environment) { String[] profiles = environment.getActiveProfiles(); if (profiles.length == 0) { profiles = environment.getDefaultProfiles(); } this.setProfile(StringUtils.arrayToCommaDelimitedString(profiles)); }
Example #19
Source File: EnableDiscoveryClientImportSelector.java From spring-cloud-commons with Apache License 2.0 | 5 votes |
@Override public String[] selectImports(AnnotationMetadata metadata) { String[] imports = super.selectImports(metadata); AnnotationAttributes attributes = AnnotationAttributes.fromMap( metadata.getAnnotationAttributes(getAnnotationClass().getName(), true)); boolean autoRegister = attributes.getBoolean("autoRegister"); if (autoRegister) { List<String> importsList = new ArrayList<>(Arrays.asList(imports)); importsList.add( "org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration"); imports = importsList.toArray(new String[0]); } else { Environment env = getEnvironment(); if (ConfigurableEnvironment.class.isInstance(env)) { ConfigurableEnvironment configEnv = (ConfigurableEnvironment) env; LinkedHashMap<String, Object> map = new LinkedHashMap<>(); map.put("spring.cloud.service-registry.auto-registration.enabled", false); MapPropertySource propertySource = new MapPropertySource( "springCloudDiscoveryClient", map); configEnv.getPropertySources().addLast(propertySource); } } return imports; }
Example #20
Source File: ApplicationConfiguration.java From bookstore-service-broker with Apache License 2.0 | 5 votes |
@Bean @ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY) public ApplicationInformation cloudFoundryApplicationInformation(Environment environment) { String uri = environment.getProperty("vcap.application.uris[0]"); String baseUrl = UriComponentsBuilder.newInstance() .scheme("https") .host(uri) .build() .toUriString(); return new ApplicationInformation(baseUrl); }
Example #21
Source File: AwsAutoConfiguration.java From genie with Apache License 2.0 | 5 votes |
/** * Provide a lazy {@link S3ClientFactory} instance if one is needed by the system. * * @param awsCredentialsProvider The {@link AWSCredentialsProvider} to use * @param awsRegionProvider The {@link AwsRegionProvider} to use * @param environment The Spring application {@link Environment} to bind properties from * @return A {@link S3ClientFactory} instance */ @Bean @ConditionalOnMissingBean(S3ClientFactory.class) public S3ClientFactory s3ClientFactory( final AWSCredentialsProvider awsCredentialsProvider, final AwsRegionProvider awsRegionProvider, final Environment environment ) { return new S3ClientFactory(awsCredentialsProvider, awsRegionProvider, environment); }
Example #22
Source File: AnnotatedBeanDefinitionReader.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Get the Environment from the given registry if possible, otherwise return a new * StandardEnvironment. */ private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) { Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); if (registry instanceof EnvironmentCapable) { return ((EnvironmentCapable) registry).getEnvironment(); } return new StandardEnvironment(); }
Example #23
Source File: CredHubCfEnvProcessorTests.java From java-cfenv with Apache License 2.0 | 5 votes |
@Test public void simpleService() { mockVcapServices(readTestDataFile("test-credhub-service.json")); Environment environment = getEnvironment(); assertThat(environment.getProperty("some.external.service.password")).isEqualTo("p4ssw0rd"); }
Example #24
Source File: DefaultRootVolumeSizeProvider.java From cloudbreak with Apache License 2.0 | 5 votes |
public DefaultRootVolumeSizeProvider(CloudPlatformConnectors cloudPlatformConnectors, Environment environment) { PlatformVariants platformVariants = cloudPlatformConnectors.getPlatformVariants(); platformVolumeSizeMap = Collections.unmodifiableMap( platformVariants.getDefaultVariants().keySet() .stream() .collect(Collectors.toMap(StringType::value, p -> initPlatform(environment, p))) ); }
Example #25
Source File: AlchemyApp.java From alchemy with Apache License 2.0 | 5 votes |
private static void logApplicationStartup(Environment env) { String protocol = "http"; if (env.getProperty("server.ssl.key-store") != null) { protocol = "https"; } String serverPort = env.getProperty("server.port"); String contextPath = env.getProperty("server.servlet.context-path"); if (StringUtils.isBlank(contextPath)) { contextPath = "/"; } String hostAddress = "localhost"; try { hostAddress = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { log.warn("The host name could not be determined, using `localhost` as fallback"); } log.info("\n----------------------------------------------------------\n\t" + "Application '{}' is running! Access URLs:\n\t" + "Local: \t\t{}://localhost:{}{}\n\t" + "External: \t{}://{}:{}{}\n\t" + "Profile(s): \t{}\n----------------------------------------------------------", env.getProperty("spring.application.name"), protocol, serverPort, contextPath, protocol, hostAddress, serverPort, contextPath, env.getActiveProfiles()); }
Example #26
Source File: AbstractCacheDataImporterExporterUnitTests.java From spring-boot-data-geode with Apache License 2.0 | 5 votes |
private Environment configureExport(Environment mockEnvironment, boolean enabled) { doReturn(enabled).when(mockEnvironment) .getProperty(eq(AbstractCacheDataImporterExporter.CACHE_DATA_EXPORT_ENABLED_PROPERTY_NAME), eq(Boolean.class), eq(AbstractCacheDataImporterExporter.DEFAULT_CACHE_DATA_EXPORT_ENABLED)); return mockEnvironment; }
Example #27
Source File: ConfigurationClassParser.java From spring-analysis-note with MIT License | 5 votes |
/** * Create a new {@link ConfigurationClassParser} instance that will be used * to populate the set of configuration classes. */ public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory, ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader, BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) { this.metadataReaderFactory = metadataReaderFactory; this.problemReporter = problemReporter; this.environment = environment; this.resourceLoader = resourceLoader; this.registry = registry; this.componentScanParser = new ComponentScanAnnotationParser( environment, resourceLoader, componentScanBeanNameGenerator, registry); this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader); }
Example #28
Source File: FunctionExporterAutoConfiguration.java From spring-cloud-function with Apache License 2.0 | 5 votes |
@Bean public RequestBuilder simpleRequestBuilder(Environment environment) { SimpleRequestBuilder builder = new SimpleRequestBuilder(environment); if (this.props.getSink().getUrl() != null) { builder.setTemplateUrl(this.props.getSink().getUrl()); } builder.setHeaders(this.props.getSink().getHeaders()); return builder; }
Example #29
Source File: DubboDefaultPropertiesEnvironmentPostProcessor.java From dubbo-spring-boot-project with Apache License 2.0 | 5 votes |
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); } }
Example #30
Source File: AutoUpdateConfigChangeListener.java From apollo with Apache License 2.0 | 5 votes |
public AutoUpdateConfigChangeListener(Environment environment, ConfigurableListableBeanFactory beanFactory){ this.typeConverterHasConvertIfNecessaryWithFieldParameter = testTypeConverterHasConvertIfNecessaryWithFieldParameter(); this.beanFactory = beanFactory; this.typeConverter = this.beanFactory.getTypeConverter(); this.environment = environment; this.placeholderHelper = SpringInjector.getInstance(PlaceholderHelper.class); this.springValueRegistry = SpringInjector.getInstance(SpringValueRegistry.class); this.gson = new Gson(); }