Java Code Examples for org.springframework.core.env.Environment#getProperty()

The following examples show how to use org.springframework.core.env.Environment#getProperty() . 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: JdbcUrlCondition.java    From logging-log4j-audit with Apache License 2.0 6 votes vote down vote up
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    Environment env = context.getEnvironment();
    Map<String, Object> map = metadata.getAnnotationAttributes(JdbcUrl.class.getName());
    if (map != null && map.containsKey("value")) {
        String value = map.get("value").toString();
        String jdbcUrl = env.getProperty("jdbcUrl");
        boolean isEmbedded = Boolean.parseBoolean(env.getProperty("isEmbedded"));
        boolean result;
        if (value.equals("hsqldb")) {
            result = jdbcUrl == null || isEmbedded;
        } else if (jdbcUrl == null || isEmbedded) {
            result = false;
        } else if (!jdbcUrl.startsWith("jdbc:")) {
            result = false;
        } else {
            result = jdbcUrl.substring(5).toLowerCase().startsWith(value.toLowerCase());
        }
        LOGGER.debug("Returning {} for {}", result, value);
        return result;
    }
    LOGGER.debug("No data provided");
    return false;
}
 
Example 2
Source File: BarApp.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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(BarApp.class);
    SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
    addDefaultProfile(app, source);
    Environment env = app.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 3
Source File: AutoConfiguredMapperScannerRegistrar.java    From AsyncDao with MIT License 6 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    log.debug("Searching for mappers annotated with @Mapper");
    ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
    try {
        if (this.resourceLoader != null) {
            scanner.setResourceLoader(this.resourceLoader);
        }
        String[] packages;
        Environment env = beanFactory.getBean(Environment.class);
        String basePackages = env.getProperty("async.dao.basePackages");
        if (StringUtils.isEmpty(basePackages)) {
            packages = StringUtils.toStringArray(AutoConfigurationPackages.get(this.beanFactory));
        } else {
            packages = basePackages.split(",");
        }
        scanner.setAnnotationClass(Mapper.class);
        scanner.registerFilters();
        scanner.doScan(packages);
    } catch (IllegalStateException ex) {
        log.debug("Could not determine auto-configuration package, automatic mapper scanning disabled.", ex);
    }
}
 
Example 4
Source File: ConfigUtils.java    From spring-cloud-kubernetes with Apache License 2.0 6 votes vote down vote up
public static <C extends AbstractConfigProperties> String getApplicationName(
		Environment env, String configName, String configurationTarget) {
	String name = configName;
	if (StringUtils.isEmpty(name)) {
		// TODO: use relaxed binding
		if (LOG.isDebugEnabled()) {
			LOG.debug(configurationTarget
					+ " name has not been set, taking it from property/env "
					+ SPRING_APPLICATION_NAME + " (default="
					+ FALLBACK_APPLICATION_NAME + ")");
		}

		name = env.getProperty(SPRING_APPLICATION_NAME, FALLBACK_APPLICATION_NAME);
	}

	return name;
}
 
Example 5
Source File: EncryptionBootstrapConfiguration.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
private boolean hasProperty(Environment environment, String key) {
	String value = environment.getProperty(key);
	if (value == null) {
		return false;
	}
	return StringUtils.hasText(environment.resolvePlaceholders(value));
}
 
Example 6
Source File: NacosPropertySourceLocator.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Override
public PropertySource<?> locate(Environment env) {
	nacosConfigProperties.setEnvironment(env);
	ConfigService configService = nacosConfigManager.getConfigService();

	if (null == configService) {
		log.warn("no instance of config service found, can't load config from nacos");
		return null;
	}
	long timeout = nacosConfigProperties.getTimeout();
	nacosPropertySourceBuilder = new NacosPropertySourceBuilder(configService,
			timeout);
	String name = nacosConfigProperties.getName();

	String dataIdPrefix = nacosConfigProperties.getPrefix();
	if (StringUtils.isEmpty(dataIdPrefix)) {
		dataIdPrefix = name;
	}

	if (StringUtils.isEmpty(dataIdPrefix)) {
		dataIdPrefix = env.getProperty("spring.application.name");
	}

	CompositePropertySource composite = new CompositePropertySource(
			NACOS_PROPERTY_SOURCE_NAME);

	loadSharedConfiguration(composite);
	loadExtConfiguration(composite);
	loadApplicationConfiguration(composite, dataIdPrefix, nacosConfigProperties, env);

	return composite;
}
 
Example 7
Source File: LookoutAutoConfiguration.java    From sofa-lookout with Apache License 2.0 5 votes vote down vote up
@Bean
public LookoutConfig lookoutConfig(LookoutClientProperties lookoutClientProperties,
                                   Environment environment) {
    String appName = environment.getProperty("spring.application.name");
    Assert.notNull(appName, "spring.application.name can not be null!");
    LookoutConfig config = buildLookoutConfig(lookoutClientProperties);
    config.setProperty(APP_NAME, appName);
    //configure
    configureLookoutConfig(config);
    return config;
}
 
Example 8
Source File: SimpleAdminConnectors.java    From canal with Apache License 2.0 5 votes vote down vote up
public static <R> R execute(String ip, int port, Function<AdminConnector, R> function) {
    Environment env = (Environment) SpringContext.getBean(Environment.class);
    String defaultUser = env.getProperty("canal.adminUser", "admin");
    String defaultPasswd = env.getProperty("canal.adminPasswd", "admin");

    return execute(ip, port, defaultUser, defaultPasswd, function);
}
 
Example 9
Source File: DynamicDataSourceRegister.java    From Aooms with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化更多数据源
 */
private void initMoreDataSources(Environment env) {
    String more = env.getProperty("spring.more-datasource.keys");
    if(StrUtil.isBlank(more)){
        return;
    }

    String[] moreDataSourceNames = more.split(",");
    for(String name : moreDataSourceNames){
        if(StrUtil.isNotBlank(name)){
            // 创建主数据源
            DataSource dataSource = buildDataSource(env,"spring.more-datasource." + name,name);
            moreDataSources.put(name, dataSource);
        }
    }


  /*  Binder binder = Binder.get(env);
    FooProperties foo = binder.bind("foo", Bindable.of(FooProperties.class)).get();

    // 读取配置文件获取更多数据源,也可以通过defaultDataSource读取数据库获取更多数据源
    RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "custom.datasource.");
    String dsPrefixs = propertyResolver.getProperty("names");
    for (String dsPrefix : dsPrefixs.split(",")) {// 多个数据源
        Map<String, Object> dsMap = propertyResolver.getSubProperties(dsPrefix + ".");
        DataSource ds = buildDataSource(dsMap);
        customDataSources.put(dsPrefix, ds);
        dataBinder(ds, env);
    }*/
}
 
Example 10
Source File: DockerPostgresDatabaseProvider.java    From embedded-database-spring-test with Apache License 2.0 5 votes vote down vote up
public DockerPostgresDatabaseProvider(Environment environment, ObjectProvider<List<PostgreSQLContainerCustomizer>> containerCustomizers) {
    String dockerImage = environment.getProperty("zonky.test.database.postgres.docker.image", "postgres:10.11-alpine");
    String tmpfsOptions = environment.getProperty("zonky.test.database.postgres.docker.tmpfs.options", "rw,noexec,nosuid");
    boolean tmpfsEnabled = environment.getProperty("zonky.test.database.postgres.docker.tmpfs.enabled", boolean.class, false);

    Map<String, String> initdbProperties = PropertyUtils.extractAll(environment, "zonky.test.database.postgres.initdb.properties");
    Map<String, String> configProperties = PropertyUtils.extractAll(environment, "zonky.test.database.postgres.server.properties");
    Map<String, String> connectProperties = PropertyUtils.extractAll(environment, "zonky.test.database.postgres.client.properties");

    List<PostgreSQLContainerCustomizer> customizers = Optional.ofNullable(containerCustomizers.getIfAvailable()).orElse(emptyList());

    this.databaseConfig = new DatabaseConfig(dockerImage, tmpfsOptions, tmpfsEnabled, initdbProperties, configProperties, customizers);
    this.clientConfig = new ClientConfig(connectProperties);
}
 
Example 11
Source File: UaaApp.java    From tutorials with MIT License 5 votes vote down vote up
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());

    String configServerStatus = env.getProperty("configserver.status");
    if (configServerStatus == null) {
        configServerStatus = "Not found or not setup for this application";
    }
    log.info("\n----------------------------------------------------------\n\t" +
            "Config Server: \t{}\n----------------------------------------------------------", configServerStatus);
}
 
Example 12
Source File: StartedUpRunner.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
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 13
Source File: ConfigurationSpringInitializer.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
/**
 * Try to get a name for identifying the environment.
 * @param environment the target that the name is generated for.
 * @return The generated name for the environment.
 */
private String generateNameForEnvironment(Environment environment) {
  String environmentName = environment.getProperty("spring.config.name");
  if (!StringUtils.isEmpty(environmentName)) {
    return environmentName;
  }

  environmentName = environment.getProperty("spring.application.name");
  if (!StringUtils.isEmpty(environmentName)) {
    return environmentName;
  }

  return environment.getClass().getName() + "@" + environment.hashCode();
}
 
Example 14
Source File: SmartSwaggerDynamicGroupConfig.java    From smart-admin with MIT License 5 votes vote down vote up
@Override
public void setEnvironment(Environment environment) {
    this.apiGroupName = environment.getProperty("swagger.apiGroupName");
    this.title = environment.getProperty("swagger.title");
    this.description = environment.getProperty("swagger.description");
    this.version = environment.getProperty("swagger.version");
    this.serviceUrl = environment.getProperty("swagger.serviceUrl");
    this.packAge = environment.getProperty("swagger.packAge");
}
 
Example 15
Source File: UiUtils.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve public address of this app, if it not configured return null.
 * @param environment env
 * @return host:port or null
 */
public static String getAppAddress(Environment environment) {
    String host = environment.getProperty("dm.server.host");
    if(host == null) {
        return null;
    }
    return host + ":" + environment.getProperty("dm.server.port");
}
 
Example 16
Source File: HashPartitionStrategyCrutch.java    From nakadi with MIT License 5 votes vote down vote up
@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 17
Source File: WebSecurityConfig.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
@Override
public void setEnvironment(Environment environment) {
	DEFAULT_SBACTXPATH = environment.getProperty("spring.boot.admin.context-path", DEFAULT_SBACTXPATH);
}
 
Example 18
Source File: SslAutoConfiguration.java    From spring-boot-data-geode with Apache License 2.0 4 votes vote down vote up
private static String resolveTrustedKeystoreName(Environment environment) {

		return environment != null && environment.containsProperty(TRUSTED_KEYSTORE_FILENAME_PROPERTY)
			? environment.getProperty(TRUSTED_KEYSTORE_FILENAME_PROPERTY)
			: TRUSTED_KEYSTORE_FILENAME;
	}
 
Example 19
Source File: ConfigUtils.java    From code-generator with MIT License 4 votes vote down vote up
public static String get(String key) {
    Environment environment = SpringContextUtils.getBean(Environment.class);
    return environment.getProperty(key);
}
 
Example 20
Source File: LoadBalancerEurekaAutoConfiguration.java    From spring-cloud-netflix with Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnMissingBean
LoadBalancerZoneConfig zoneConfig(Environment environment) {
	return new LoadBalancerZoneConfig(environment.getProperty(LOADBALANCER_ZONE));
}