org.springframework.context.ConfigurableApplicationContext#getEnvironment ( )源码实例Demo

下面列出了org.springframework.context.ConfigurableApplicationContext#getEnvironment ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: jasypt-spring-boot   文件: AbstractJasyptMojo.java
@Override
public void execute() throws MojoExecutionException {
    Map<String, Object> defaultProperties = new HashMap<>();
    defaultProperties.put("spring.config.location", "file:./src/main/resources/");

    ConfigurableApplicationContext context = new SpringApplicationBuilder()
            .sources(Application.class)
            .bannerMode(Banner.Mode.OFF)
            .properties(defaultProperties)
            .run();

    this.environment = context.getEnvironment();

    String[] activeProfiles = context.getEnvironment().getActiveProfiles();
    String profiles = activeProfiles.length != 0 ? String.join(",", activeProfiles) : "Default";
    log.info("Active Profiles: {}", profiles);
    StringEncryptor encryptor = context.getBean(StringEncryptor.class);
    run(new EncryptionService(encryptor), context, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix);
}
 
public static void main(String[] args) {
    ConfigurableApplicationContext context =
            new SpringApplicationBuilder(AttachedEnvironmentBootstrap.class)
                    .web(WebApplicationType.NONE) // 非 Web 应用
                    .properties("relaxed.NAME=小马哥")
                    .run(args);
    // 获取 ConfigurableEnvironment 对象
    ConfigurableEnvironment environment = context.getEnvironment();

    System.out.printf("Environment 获取属性 - 松散方式 relaxed.name :%s , 原始方式 relaxed.NAME :%s\n",
            environment.getProperty("relaxed.name"), environment.getProperty("relaxed.NAME"));

    // 从 Environment 关联的 MutablePropertySources 移除 ConfigurationPropertySourcesPropertySource
    System.out.printf("PropertySource[ %s ] 已从 Environment 中删除!\n",
            environment.getPropertySources().remove("configurationProperties"));

    System.out.printf("Environment 获取属性 - 松散方式 relaxed.name :%s , 原始方式 relaxed.NAME :%s\n",
            environment.getProperty("relaxed.name"), environment.getProperty("relaxed.NAME"));

    // 关闭上下文
    context.close();
}
 
源代码3 项目: spring-cloud-function   文件: FunctionInvoker.java
private void start() {
	ConfigurableApplicationContext context = SpringApplication.run(FunctionClassUtils.getStartClass());
	Environment environment = context.getEnvironment();
	String functionName = environment.getProperty("spring.cloud.function.definition");
	FunctionCatalog functionCatalog = context.getBean(FunctionCatalog.class);
	this.mapper = context.getBean(ObjectMapper.class);
	this.configureObjectMapper();

	if (logger.isInfoEnabled()) {
		logger.info("Locating function: '" + functionName + "'");
	}

	this.function = functionCatalog.lookup(functionName, "application/json");
	Assert.notNull(this.function, "Failed to lookup function " + functionName);

	if (!StringUtils.hasText(functionName)) {
		FunctionInspector inspector = context.getBean(FunctionInspector.class);
		functionName = inspector.getRegistration(this.function).getNames().toString();
	}

	if (logger.isInfoEnabled()) {
		logger.info("Located function: '" + functionName + "'");
	}
}
 
public static void main(String[] args) {
    ConfigurableApplicationContext context =
            new SpringApplicationBuilder(ExtendPropertySourcesBootstrap.class)
                    .web(WebApplicationType.NONE) // 非 Web 应用
                    .run(args);

    // 获取 Environment
    ConfigurableEnvironment environment = context.getEnvironment();
    // 加载 META-INF/runtime.properties 配置文件
    ResourcePropertySource propertySource = PropertySourceUtils.getResourcePropertySource("META-INF/runtime.properties");
    // 追加至 PropertySources 顶端
    environment.getPropertySources().addFirst(propertySource);
    // 读取 user.name 属性内容
    System.out.println("从 Environment 读取属性 user.name = " + environment.getProperty("user.name"));
    System.out.println("Environment 所有 PropertySource : ");

    environment.getPropertySources().forEach(source -> {
        System.out.printf("\t %s\n", source);
    });
    // 关闭上下文
    context.close();
}
 
源代码5 项目: jeewx-boot   文件: JeewxBootApplication.java
public static void main(String[] args) throws UnknownHostException {
	ConfigurableApplicationContext application = SpringApplication.run(JeewxBootApplication.class, args);
    Environment env = application.getEnvironment();
    String ip = InetAddress.getLocalHost().getHostAddress();
    String port = env.getProperty("server.port");
    String path = env.getProperty("server.servlet.context-path");
    log.info("\n----------------------------------------------------------\n\t" +
        "Application Jeewx-Boot is running! Access URLs:\n\t" +
        "Local: \t\thttp://localhost:" + port + path + "/\n\t" +
        "External: \thttp://" + ip + ":" + port + path + "/\n\t" +
        "----------------------------------------------------------");
}
 
public static void main(String[] args) throws UnknownHostException {
    ConfigurableApplicationContext application = SpringApplication.run(DemoServerApplication.class, args);
    Environment env = application.getEnvironment();
    log.info("\n----------------------------------------------------------\n\t" +
                    "应用 '{}' 运行成功! 访问连接:\n\t" +
                    "Swagger文档: \t\thttp://{}:{}/doc.html\n" +
                    "----------------------------------------------------------",
            env.getProperty("spring.application.name"),
            InetAddress.getLocalHost().getHostAddress(),
            env.getProperty("server.port"));

}
 
@Override
public void initialize(ConfigurableApplicationContext aApplicationContext)
{
    ConfigurableEnvironment aEnvironment = aApplicationContext.getEnvironment();

    File settings = SettingsUtil.getSettingsFile();
    
    // If settings were found, add them to the environment
    if (settings != null) {
        log.info("Settings: " + settings);
        try {
            aEnvironment.getPropertySources().addFirst(
                    new ResourcePropertySource(new FileSystemResource(settings)));
        }
        catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    // Activate bean profile depending on authentication mode
    if (AUTH_MODE_PREAUTH.equals(aEnvironment.getProperty(SettingsUtil.CFG_AUTH_MODE))) {
        aEnvironment.setActiveProfiles(PROFILE_PREAUTH);
        log.info("Authentication: pre-auth");
    }
    else {
        aEnvironment.setActiveProfiles(PROFILE_DATABASE);
        log.info("Authentication: database");
    }
}
 
@Override
public void initialize(ConfigurableApplicationContext context) {
	singleton.setApplicationContext(context);
	environment = context.getEnvironment();
	nacosConfigProperties = NacosConfigPropertiesUtils
			.buildNacosConfigProperties(environment);
	final NacosConfigLoader configLoader = new NacosConfigLoader(
			nacosConfigProperties, environment, builder);
	if (!enable()) {
		logger.info("[Nacos Config Boot] : The preload configuration is not enabled");
	}
	else {

		// If it opens the log level loading directly will cache
		// DeferNacosPropertySource release

		if (processor.enable()) {
			processor.publishDeferService(context);
			configLoader
					.addListenerIfAutoRefreshed(processor.getDeferPropertySources());
		}
		else {
			configLoader.loadConfig();
			configLoader.addListenerIfAutoRefreshed();
		}
	}

	final ConfigurableListableBeanFactory factory = context.getBeanFactory();
	if (!factory
			.containsSingleton(NacosBeanUtils.GLOBAL_NACOS_PROPERTIES_BEAN_NAME)) {
		factory.registerSingleton(NacosBeanUtils.GLOBAL_NACOS_PROPERTIES_BEAN_NAME,
				configLoader.buildGlobalNacosProperties());
	}
}
 
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
	ConfigurableEnvironment environment = applicationContext.getEnvironment();
	MutablePropertySources propertySources = environment.getPropertySources();

	String[] defaultKeys = {"password", "secret", "key", "token", ".*credentials.*", "vcap_services"};
	Set<String> propertiesToSanitize = Stream.of(defaultKeys)
											 .collect(Collectors.toSet());

	PropertySource<?> bootstrapProperties = propertySources.get(BOOTSTRAP_PROPERTY_SOURCE_NAME);
	Set<PropertySource<?>> bootstrapNestedPropertySources = new HashSet<>();
	Set<PropertySource<?>> configServiceNestedPropertySources = new HashSet<>();

	if (bootstrapProperties != null && bootstrapProperties instanceof CompositePropertySource) {
		bootstrapNestedPropertySources.addAll(((CompositePropertySource) bootstrapProperties).getPropertySources());
	}
	for (PropertySource<?> nestedProperty : bootstrapNestedPropertySources) {
		if (nestedProperty.getName().equals(CONFIG_SERVICE_PROPERTY_SOURCE_NAME)) {
			configServiceNestedPropertySources.addAll(((CompositePropertySource) nestedProperty).getPropertySources());
		}
	}

	Stream<String> vaultKeyNameStream =
			configServiceNestedPropertySources.stream()
											  .filter(ps -> ps instanceof EnumerablePropertySource)
											  .filter(ps -> ps.getName().startsWith(VAULT_PROPERTY_PATTERN) || ps.getName().startsWith(CREDHUB_PROPERTY_PATTERN))
											  .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames())
											  .flatMap(Arrays::<String>stream);

	propertiesToSanitize.addAll(vaultKeyNameStream.collect(Collectors.toSet()));

	PropertiesPropertySource envKeysToSanitize =
			new PropertiesPropertySource(
					SANITIZE_ENV_KEY, mergeClientProperties(propertySources, propertiesToSanitize));

	environment.getPropertySources().addFirst(envKeysToSanitize);
	applicationContext.setEnvironment(environment);

}
 
源代码10 项目: code   文件: ProductApplication.java
public static void main(String[] args) throws UnknownHostException {
    ConfigurableApplicationContext application = SpringApplication.run(ProductApplication.class, args);
    Environment env = application.getEnvironment();
    String ip = InetAddress.getLocalHost().getHostAddress();
    String port = env.getProperty("server.port")==null?"":env.getProperty("server.port");
    String path = env.getProperty("server.servlet.context-path")==null?"":env.getProperty("server.servlet.context-path");
    log.info("\n----------------------------------------------------------\n\t" +
            "Application hotel-query-service is running! Access URLs:\n\t" +
            "Local: \t\thttp://localhost:" + port + path + "/\n\t" +
            "External: \thttp://" + ip + ":" + port + path + "/\n\t" +
            "swagger-ui: \thttp://" + ip + ":" + port + path + "/swagger-ui.html\n\t" +
            "----------------------------------------------------------");
}
 
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
	ConfigurableEnvironment applicationEnvironment = applicationContext.getEnvironment();
	Cloud cloud = getCloud();
	if (cloud != null) {
		applicationEnvironment.addActiveProfile("cloud");

	} else {
		applicationEnvironment.addActiveProfile("local");
	}

}
 
源代码12 项目: spring-boot-plus   文件: PrintApplicationInfo.java
/**
 * 执行之前,打印前置条件提示
 */
public static void printTip(ConfigurableApplicationContext context) {
    ConfigurableEnvironment environment = context.getEnvironment();
    // 项目profile
    String profileActive = environment.getProperty("spring.profiles.active");
    StringBuffer tip = new StringBuffer();
    tip.append("===========================================================================================\n");
    tip.append("                                                                                  \n");
    tip.append("                               !!!准备工作!!!                                      \n");
    tip.append(" 1.导入SQL初始化脚本:docs/db,根据不同数据库导入对应SQL脚本并修改链接等信息配置\n");
    tip.append(" 2.启动Redis服务,必要条件\n");
    tip.append(" 3.启动SpringBootAdmin Server,可选操作,admin模块中,启动SpringBootPlusAdminApplication\n");
    tip.append(" 4.根据项目需要,修改项目配置,请先查看官网配置文档:https://springboot.plus/config/\n");
    tip.append(" 5.项目模块说明:\n");
    tip.append("    admin:       SpringBootAdmin Server启动模块\n");
    tip.append("    bootstrap:   项目启动模块\n");
    tip.append("    config:      项目配置模块\n");
    tip.append("    distribution:项目打包模块,打包时,请先选中Maven Profiles中的release和对应环境\n");
    tip.append("    example:     业务自定义模块,自己的业务代码可在example下进行,也可以再创建模块\n");
    tip.append("    framework:   项目核心框架模块\n");
    tip.append("    generator:   代码生成模块,启动类:SpringBootPlusGenerator,请根据实际情况进行配置\n");
    tip.append("    scheduled:   任务调度模块\n");
    tip.append("    system:      系统管理模块\n");
    tip.append(" 6.FAQ:https://springboot.plus/faq\n");
    tip.append(" 7.如开发中遇到bug及问题,欢迎提交ISSUES:https://github.com/geekidea/spring-boot-plus/issues\n");
    tip.append(" 8.QQ:625301326,进群答案:springboot.plus\n");
    tip.append("                                                                                  \n");
    tip.append("===========================================================================================\n");
    if ("dev".equals(profileActive)) {
        log.info("\n{}", Ansi.ansi().eraseScreen().fg(Ansi.Color.YELLOW).a(tip.toString()).reset().toString());
    }
}
 
public static void main(String[] args) {
    ConfigurableApplicationContext context =
            new SpringApplicationBuilder(
                    SpringApplicationJsonPropertySourceBootstrap.class)
                    // SpringApplication Properties 设置 JSON内容(优先级最低)
                    .properties("spring.application.json={\"my.name\":\"小马哥\"}")
                    .web(WebApplicationType.NONE) // 非 Web 应用
                    .run(args);

    ConfigurableEnvironment environment = context.getEnvironment();
    // 读取 spring.application.json 属性
    System.out.println("my.name = " + environment.getProperty("my.name"));
    // 关闭上下文
    context.close();
}
 
源代码14 项目: albedo   文件: ApplicationLoggerInitializer.java
@Override
	public void initialize(ConfigurableApplicationContext applicationContext) {
		ConfigurableEnvironment environment = applicationContext.getEnvironment();

		String logPath = environment.getProperty("application.logPath");
		String applicationName = environment.getProperty("spring.application.name");

//		String logBase = environment.getProperty("LOGGING_PATH", "logs");
		// spring boot sys 直接加载日志
		System.setProperty("logging.file", String.format("%s/%s/debug.log", logPath, applicationName));
	}
 
源代码15 项目: sofa-common-tools   文件: LogbackIntegrationTest.java
/**
 * test space config override global config
 * @throws IOException
 */
@Test
public void testSpaceOverrideGlobalConfig() throws IOException {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(Constants.SOFA_MIDDLEWARE_ALL_LOG_CONSOLE_SWITCH, "true");
    properties.put(Constants.SOFA_MIDDLEWARE_ALL_LOG_CONSOLE_LEVEL, "debug");
    properties
        .put(String.format(Constants.SOFA_MIDDLEWARE_SINGLE_LOG_CONSOLE_SWITCH, TEST_SPACE),
            "false");
    properties.put(
        String.format(Constants.SOFA_MIDDLEWARE_SINGLE_LOG_CONSOLE_LEVEL, TEST_SPACE), "info");

    SpringApplication springApplication = new SpringApplication(EmptyConfig.class);
    springApplication.setDefaultProperties(properties);
    springApplication.run(new String[] {});
    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");
    logger.debug("debug 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("info level"));
    Assert.assertFalse(outContent.toString().contains("info level"));
    Assert.assertFalse(outContent.toString().contains("debug level"));
    LogEnvUtils.processGlobalSystemLogProperties().remove(
        Constants.SOFA_MIDDLEWARE_ALL_LOG_CONSOLE_SWITCH);
    LogEnvUtils.processGlobalSystemLogProperties().remove(
        Constants.SOFA_MIDDLEWARE_ALL_LOG_CONSOLE_LEVEL);
    LogEnvUtils.processGlobalSystemLogProperties().remove(
        String.format(Constants.SOFA_MIDDLEWARE_SINGLE_LOG_CONSOLE_SWITCH, TEST_SPACE));
    LogEnvUtils.processGlobalSystemLogProperties().remove(
        String.format(Constants.SOFA_MIDDLEWARE_SINGLE_LOG_CONSOLE_LEVEL, TEST_SPACE));
}
 
源代码16 项目: zuihou-admin-cloud   文件: OauthApplication.java
public static void main(String[] args) throws UnknownHostException {
    ConfigurableApplicationContext application = SpringApplication.run(OauthApplication.class, args);
    Environment env = application.getEnvironment();
    log.info("\n----------------------------------------------------------\n\t" +
                    "应用 '{}' 运行成功! 访问连接:\n\t" +
                    "Swagger文档: \t\thttp://{}:{}/doc.html\n\t" +
                    "数据库监控: \t\thttp://{}:{}/druid\n" +
                    "----------------------------------------------------------",
            env.getProperty("spring.application.name"),
            InetAddress.getLocalHost().getHostAddress(),
            env.getProperty("server.port"),
            "127.0.0.1",
            env.getProperty("server.port"));
}
 
public static void main(String[] args) {
    ConfigurableApplicationContext run = SpringApplication.run(TraceServiceA15xSpringBootApplication.class, args);
    ConfigurableEnvironment environment = run.getEnvironment();
    log.info("启动");
}
 
public static void main(String[] args) {
    ConfigurableApplicationContext run = SpringApplication.run(TraceServiceASpringBootApplication.class, args);
    ConfigurableEnvironment environment = run.getEnvironment();
    log.info("启动");
}
 
public static void main(String[] args) {
    ConfigurableApplicationContext run = SpringApplication.run(TraceServiceBSpringBootApplication.class, args);
    ConfigurableEnvironment environment = run.getEnvironment();
    log.info("启动");
}
 
源代码20 项目: fredbet   文件: AppInitializer.java
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
	final ConfigurableEnvironment environment = applicationContext.getEnvironment();

	LOG.info("Active profiles: {}", Arrays.asList(environment.getActiveProfiles()));
}