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

The following examples show how to use org.springframework.core.env.Environment#getProperty() . These examples are extracted from open source projects. 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
@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
@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 3
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 4
/**
 * 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 5
Source Project: nakadi   File: HashPartitionStrategyCrutch.java    License: 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 6
Source Project: haven-platform   File: UiUtils.java    License: 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 7
@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 8
/**
 * 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 9
Source Project: FEBS-Cloud   File: StartedUpRunner.java    License: 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 10
Source Project: tutorials   File: UaaApp.java    License: 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 11
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 12
Source Project: Aooms   File: DynamicDataSourceRegister.java    License: 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 13
Source Project: canal   File: SimpleAdminConnectors.java    License: 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 14
@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 15
@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 16
private boolean hasProperty(Environment environment, String key) {
	String value = environment.getProperty(key);
	if (value == null) {
		return false;
	}
	return StringUtils.hasText(environment.resolvePlaceholders(value));
}
 
Example 17
@Bean
@ConditionalOnMissingBean
LoadBalancerZoneConfig zoneConfig(Environment environment) {
	return new LoadBalancerZoneConfig(environment.getProperty(LOADBALANCER_ZONE));
}
 
Example 18
@Override
public void setEnvironment(Environment environment) {
	DEFAULT_SBACTXPATH = environment.getProperty("spring.boot.admin.context-path", DEFAULT_SBACTXPATH);
}
 
Example 19
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 20
Source Project: code-generator   File: ConfigUtils.java    License: MIT License 4 votes vote down vote up
public static String get(String key) {
    Environment environment = SpringContextUtils.getBean(Environment.class);
    return environment.getProperty(key);
}