类org.springframework.core.io.support.ResourcePropertySource源码实例Demo

下面列出了怎么用org.springframework.core.io.support.ResourcePropertySource的API类实例代码及写法,或者点击链接到github查看源代码。

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();
}
 
源代码2 项目: proctor   文件: PropertiesInitializer.java
protected boolean tryAddPropertySource(final ConfigurableApplicationContext applicationContext,
                                       final MutablePropertySources propSources,
                                       final String filePath) {

    if (filePath == null) {
        return false;
    }
    Resource propertiesResource = applicationContext.getResource(filePath);
    if (!propertiesResource.exists()) {
        return false;
    }
    try {
        ResourcePropertySource propertySource = new ResourcePropertySource(propertiesResource);
        propSources.addFirst(propertySource);
    } catch (IOException e) {
        return false;
    }
    return true;
}
 
源代码3 项目: gazpachoquest   文件: EnviromentDiscovery.java
@Override
public void initialize(ConfigurableApplicationContext ctx) {
    ConfigurableEnvironment environment = ctx.getEnvironment();
    String activeProfiles[] = environment.getActiveProfiles();

    if (activeProfiles.length == 0) {
        environment.setActiveProfiles("test,db_hsql");
    }

    logger.info("Application running using profiles: {}", Arrays.toString(environment.getActiveProfiles()));

    String instanceInfoString = environment.getProperty(GAZPACHO_APP_KEY);

    String dbEngine = null;
    for (String profile : activeProfiles) {
        if (profile.startsWith("db_")) {
            dbEngine = profile;
            break;
        }
    }
    try {
        environment.getPropertySources().addLast(
                new ResourcePropertySource(String.format("classpath:/database/%s.properties", dbEngine)));
    } catch (IOException e) {
        throw new IllegalStateException(dbEngine + ".properties not found in classpath", e);
    }

    PropertySourcesPlaceholderConfigurer propertyHolder = new PropertySourcesPlaceholderConfigurer();

    Map<String, String> environmentProperties = parseInstanceInfo(instanceInfoString);
    if (!environmentProperties.isEmpty()) {
        logger.info("Overriding default properties with {}", instanceInfoString);
        Properties properties = new Properties();
        for (String key : environmentProperties.keySet()) {
            String value = environmentProperties.get(key);
            properties.put(key, value);
        }
        environment.getPropertySources().addLast(new PropertiesPropertySource("properties", properties));

        propertyHolder.setEnvironment(environment);
        // ctx.addBeanFactoryPostProcessor(propertyHolder);
        // ctx.refresh();
    }
}
 
@Before
public void before() throws IOException {

    context = new AnnotationConfigApplicationContext();
    ResourcePropertySource propertySource = new ResourcePropertySource("META-INF/config.properties");
    context.getEnvironment().getPropertySources().addFirst(propertySource);

}
 
private void addPropertySource(PropertySource<?> propertySource) {
	String name = propertySource.getName();
	MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();

	if (this.propertySourceNames.contains(name)) {
		// We've already added a version, we need to extend it
		PropertySource<?> existing = propertySources.get(name);
		if (existing != null) {
			PropertySource<?> newSource = (propertySource instanceof ResourcePropertySource ?
					((ResourcePropertySource) propertySource).withResourceName() : propertySource);
			if (existing instanceof CompositePropertySource) {
				((CompositePropertySource) existing).addFirstPropertySource(newSource);
			}
			else {
				if (existing instanceof ResourcePropertySource) {
					existing = ((ResourcePropertySource) existing).withResourceName();
				}
				CompositePropertySource composite = new CompositePropertySource(name);
				composite.addPropertySource(newSource);
				composite.addPropertySource(existing);
				propertySources.replace(name, composite);
			}
			return;
		}
	}

	if (this.propertySourceNames.isEmpty()) {
		propertySources.addLast(propertySource);
	}
	else {
		String firstProcessed = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
		propertySources.addBefore(firstProcessed, propertySource);
	}
	this.propertySourceNames.add(name);
}
 
private void addPropertySource(PropertySource<?> propertySource) {
	String name = propertySource.getName();
	MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();

	if (this.propertySourceNames.contains(name)) {
		// We've already added a version, we need to extend it
		PropertySource<?> existing = propertySources.get(name);
		if (existing != null) {
			PropertySource<?> newSource = (propertySource instanceof ResourcePropertySource ?
					((ResourcePropertySource) propertySource).withResourceName() : propertySource);
			if (existing instanceof CompositePropertySource) {
				((CompositePropertySource) existing).addFirstPropertySource(newSource);
			}
			else {
				if (existing instanceof ResourcePropertySource) {
					existing = ((ResourcePropertySource) existing).withResourceName();
				}
				CompositePropertySource composite = new CompositePropertySource(name);
				composite.addPropertySource(newSource);
				composite.addPropertySource(existing);
				propertySources.replace(name, composite);
			}
			return;
		}
	}

	if (this.propertySourceNames.isEmpty()) {
		propertySources.addLast(propertySource);
	}
	else {
		String firstProcessed = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
		propertySources.addBefore(firstProcessed, propertySource);
	}
	this.propertySourceNames.add(name);
}
 
源代码7 项目: bisq-core   文件: BisqEnvironment.java
PropertySource<?> getAppDirProperties() throws Exception {
    Resource resource = getAppDirPropertiesResource();

    if (!resource.exists())
        return new PropertySource.StubPropertySource(BISQ_APP_DIR_PROPERTY_SOURCE_NAME);

    return new ResourcePropertySource(BISQ_APP_DIR_PROPERTY_SOURCE_NAME, resource);
}
 
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
    // 调用工具类 PropertySourceUtils 获取 ResourcePropertySource
    ResourcePropertySource propertySource = PropertySourceUtils.getResourcePropertySource("/META-INF/run-listener.properties");
    // 添加至最高优先级
    environment.getPropertySources().addFirst(propertySource);
}
 
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    // 从事件获取 Environment 对象
    ConfigurableEnvironment environment = event.getEnvironment();
    // 调用工具类 PropertySourceUtils 获取 ResourcePropertySource
    ResourcePropertySource propertySource = PropertySourceUtils.getResourcePropertySource("META-INF/listener.properties");
    // 添加至最高优先级
    environment.getPropertySources().addFirst(propertySource);
}
 
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    String location = "https://raw.githubusercontent.com/mercyblitz/tmp/master/remote.properties";
    // 调用工具类 PropertySourceUtils 获取 ResourcePropertySource
    ResourcePropertySource propertySource = PropertySourceUtils.getResourcePropertySource(location);
    // 添加至最高优先级
    environment.getPropertySources().addFirst(propertySource);
}
 
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    ConfigurableEnvironment environment = applicationContext.getEnvironment();
    // 调用工具类 PropertySourceUtils 获取 ResourcePropertySource
    ResourcePropertySource propertySource = PropertySourceUtils.getResourcePropertySource("META-INF/initializer.properties");
    // 添加至最高优先级
    environment.getPropertySources().addFirst(propertySource);
}
 
public static void main(String[] args) {
    // 调用工具类 PropertySourceUtils 获取 ResourcePropertySource
    ResourcePropertySource propertySource = PropertySourceUtils.getResourcePropertySource(
            "https://raw.githubusercontent.com/mercyblitz/tmp/master/remote.properties");
    // 输出 Properties 内容
    Stream.of(propertySource.getPropertyNames())                          // 将 String 转化为 Stream 对象
            .map(name -> name + " = " + propertySource.getProperty(name)) // 将 key 转化为 key = value 的形式
            .forEach(System.out::println);
}
 
@Override
public void initialize(ConfigurableApplicationContext aApplicationContext)
{
    LoggingFilter.setLoggingUsername("SYSTEM");
            
    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");
    }
}
 
源代码14 项目: ambari-logsearch   文件: LogFeederProps.java
@PostConstruct
public void init() {
  properties = new Properties();
  MutablePropertySources propSrcs = ((AbstractEnvironment) env).getPropertySources();
  ResourcePropertySource propertySource = (ResourcePropertySource) propSrcs.get("class path resource [" +
    LogFeederConstants.LOGFEEDER_PROPERTIES_FILE + "]");
  if (propertySource != null) {
    Stream.of(propertySource)
      .map(MapPropertySource::getPropertyNames)
      .flatMap(Arrays::<String>stream)
      .forEach(propName -> properties.setProperty(propName, env.getProperty(propName)));
  } else {
    throw new IllegalArgumentException("Cannot find logfeeder.properties on the classpath");
  }
}
 
源代码15 项目: seed   文件: JasyptConfiguration.java
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    MutablePropertySources propertySources = ((ConfigurableEnvironment)environment).getPropertySources();
    for(org.springframework.core.env.PropertySource<?> obj : propertySources){
        if(obj instanceof ResourcePropertySource){
            propertySources.replace(obj.getName(), new PropertySourceWrapper((ResourcePropertySource)obj));
        }
    }
}
 
源代码16 项目: lams   文件: ConfigurationClassParser.java
private void addPropertySource(PropertySource<?> propertySource) {
	String name = propertySource.getName();
	MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();
	if (propertySources.contains(name) && this.propertySourceNames.contains(name)) {
		// We've already added a version, we need to extend it
		PropertySource<?> existing = propertySources.get(name);
		PropertySource<?> newSource = (propertySource instanceof ResourcePropertySource ?
				((ResourcePropertySource) propertySource).withResourceName() : propertySource);
		if (existing instanceof CompositePropertySource) {
			((CompositePropertySource) existing).addFirstPropertySource(newSource);
		}
		else {
			if (existing instanceof ResourcePropertySource) {
				existing = ((ResourcePropertySource) existing).withResourceName();
			}
			CompositePropertySource composite = new CompositePropertySource(name);
			composite.addPropertySource(newSource);
			composite.addPropertySource(existing);
			propertySources.replace(name, composite);
		}
	}
	else {
		if (this.propertySourceNames.isEmpty()) {
			propertySources.addLast(propertySource);
		}
		else {
			String firstProcessed = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
			propertySources.addBefore(firstProcessed, propertySource);
		}
	}
	this.propertySourceNames.add(name);
}
 
private void addPropertySource(ResourcePropertySource propertySource) {
	String name = propertySource.getName();
	MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();
	if (propertySources.contains(name) && this.propertySourceNames.contains(name)) {
		// We've already added a version, we need to extend it
		PropertySource<?> existing = propertySources.get(name);
		if (existing instanceof CompositePropertySource) {
			((CompositePropertySource) existing).addFirstPropertySource(propertySource.withResourceName());
		}
		else {
			if (existing instanceof ResourcePropertySource) {
				existing = ((ResourcePropertySource) existing).withResourceName();
			}
			CompositePropertySource composite = new CompositePropertySource(name);
			composite.addPropertySource(propertySource.withResourceName());
			composite.addPropertySource(existing);
			propertySources.replace(name, composite);
		}
	}
	else {
		if (this.propertySourceNames.isEmpty()) {
			propertySources.addLast(propertySource);
		}
		else {
			String firstProcessed = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
			propertySources.addBefore(firstProcessed, propertySource);
		}
	}
	this.propertySourceNames.add(name);
}
 
源代码18 项目: c2mon   文件: C2monApplicationListener.java
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
  ConfigurableEnvironment environment = event.getEnvironment();
  String propertySource = environment.getProperty("c2mon.client.conf.url");

  if (propertySource != null) {
    try {
      environment.getPropertySources().addAfter("systemEnvironment", new ResourcePropertySource(propertySource));
    } catch (IOException e) {
      throw new RuntimeException("Could not read property source", e);
    }
  }
}
 
源代码19 项目: c2mon   文件: CommonModule.java
/**
 * Listens for the {@link ApplicationEnvironmentPreparedEvent} and injects
 * ${c2mon.server.properties} into the environment with the highest precedence
 * (if it exists). This is in order to allow users to point to an external
 * properties file via ${c2mon.server.properties}.
 */
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
  ConfigurableEnvironment environment = event.getEnvironment();
  String propertySource = environment.getProperty("c2mon.server.properties");

  if (propertySource != null) {
    try {
      environment.getPropertySources().addAfter("systemEnvironment", new ResourcePropertySource(propertySource));
    } catch (IOException e) {
      throw new RuntimeException("Could not read property source", e);
    }
  }
}
 
@Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
    String filename = resource.getResource().getFilename();

    if (filename != null && filename.endsWith(YML_FILE_EXTENSION)) {
        return name != null ? new YamlResourcePropertySource(name, resource) : new YamlResourcePropertySource(getNameForResource(resource.getResource()), resource);
    }

    return (name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource));
}
 
@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");
    }
}
 
源代码22 项目: salespoint   文件: ChangelogCreator.java
private static RestTemplate setUpRestTemplate() throws IOException {

		FileSystemResource resource = new FileSystemResource("env.properties");
		ResourcePropertySource propertySource = new ResourcePropertySource(resource);
		String username = propertySource.getProperty("github.username").toString();
		String password = propertySource.getProperty("github.password").toString();

		BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
		credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

		AuthCache authCache = new BasicAuthCache();
		authCache.put(new HttpHost("api.github.com", 443, "https"), new BasicScheme());

		final HttpClientContext context = HttpClientContext.create();
		context.setCredentialsProvider(credentialsProvider);
		context.setAuthCache(authCache);

		ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().build()) {

			@Override
			protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
				return context;
			}
		};

		RestTemplate template = new RestTemplate();
		template.setRequestFactory(factory);

		return template;
	}
 
/**
 * Add the {@link Properties} files from the given resource {@code locations}
 * to the supplied {@link ConfigurableEnvironment environment}.
 * <p>Property placeholders in resource locations (i.e., <code>${...}</code>)
 * will be {@linkplain Environment#resolveRequiredPlaceholders(String) resolved}
 * against the {@code Environment}.
 * <p>Each properties file will be converted to a {@link ResourcePropertySource}
 * that will be added to the {@link PropertySources} of the environment with
 * highest precedence.
 * @param environment the environment to update; never {@code null}
 * @param resourceLoader the {@code ResourceLoader} to use to load each resource;
 * never {@code null}
 * @param locations the resource locations of {@code Properties} files to add
 * to the environment; potentially empty but never {@code null}
 * @throws IllegalStateException if an error occurs while processing a properties file
 * @since 4.3
 * @see ResourcePropertySource
 * @see TestPropertySource#locations
 * @see #addPropertiesFilesToEnvironment(ConfigurableApplicationContext, String...)
 */
public static void addPropertiesFilesToEnvironment(ConfigurableEnvironment environment,
		ResourceLoader resourceLoader, String... locations) {

	Assert.notNull(environment, "'environment' must not be null");
	Assert.notNull(resourceLoader, "'resourceLoader' must not be null");
	Assert.notNull(locations, "'locations' must not be null");
	try {
		for (String location : locations) {
			String resolvedLocation = environment.resolveRequiredPlaceholders(location);
			Resource resource = resourceLoader.getResource(resolvedLocation);
			environment.getPropertySources().addFirst(new ResourcePropertySource(resource));
		}
	}
	catch (IOException ex) {
		throw new IllegalStateException("Failed to add PropertySource to Environment", ex);
	}
}
 
/**
 * Add the {@link Properties} files from the given resource {@code locations}
 * to the supplied {@link ConfigurableEnvironment environment}.
 * <p>Property placeholders in resource locations (i.e., <code>${...}</code>)
 * will be {@linkplain Environment#resolveRequiredPlaceholders(String) resolved}
 * against the {@code Environment}.
 * <p>Each properties file will be converted to a {@link ResourcePropertySource}
 * that will be added to the {@link PropertySources} of the environment with
 * highest precedence.
 * @param environment the environment to update; never {@code null}
 * @param resourceLoader the {@code ResourceLoader} to use to load each resource;
 * never {@code null}
 * @param locations the resource locations of {@code Properties} files to add
 * to the environment; potentially empty but never {@code null}
 * @throws IllegalStateException if an error occurs while processing a properties file
 * @since 4.3
 * @see ResourcePropertySource
 * @see TestPropertySource#locations
 * @see #addPropertiesFilesToEnvironment(ConfigurableApplicationContext, String...)
 */
public static void addPropertiesFilesToEnvironment(ConfigurableEnvironment environment,
		ResourceLoader resourceLoader, String... locations) {

	Assert.notNull(environment, "'environment' must not be null");
	Assert.notNull(resourceLoader, "'resourceLoader' must not be null");
	Assert.notNull(locations, "'locations' must not be null");
	try {
		for (String location : locations) {
			String resolvedLocation = environment.resolveRequiredPlaceholders(location);
			Resource resource = resourceLoader.getResource(resolvedLocation);
			environment.getPropertySources().addFirst(new ResourcePropertySource(resource));
		}
	}
	catch (IOException ex) {
		throw new IllegalStateException("Failed to add PropertySource to Environment", ex);
	}
}
 
源代码25 项目: seed   文件: JasyptConfiguration.java
PropertySourceWrapper(ResourcePropertySource propertySource) {
    super(propertySource.getName(), propertySource.getSource());
}
 
/**
 * Add the {@link Properties} files from the given resource {@code locations}
 * to the {@link Environment} of the supplied {@code context}.
 * <p>Property placeholders in resource locations (i.e., <code>${...}</code>)
 * will be {@linkplain Environment#resolveRequiredPlaceholders(String) resolved}
 * against the {@code Environment}.
 * <p>Each properties file will be converted to a {@link ResourcePropertySource}
 * that will be added to the {@link PropertySources} of the environment with
 * highest precedence.
 * @param context the application context whose environment should be updated;
 * never {@code null}
 * @param locations the resource locations of {@code Properties} files to add
 * to the environment; potentially empty but never {@code null}
 * @since 4.1.5
 * @see ResourcePropertySource
 * @see TestPropertySource#locations
 * @throws IllegalStateException if an error occurs while processing a properties file
 */
public static void addPropertiesFilesToEnvironment(ConfigurableApplicationContext context,
		String[] locations) {
	Assert.notNull(context, "context must not be null");
	Assert.notNull(locations, "locations must not be null");
	try {
		ConfigurableEnvironment environment = context.getEnvironment();
		for (String location : locations) {
			String resolvedLocation = environment.resolveRequiredPlaceholders(location);
			Resource resource = context.getResource(resolvedLocation);
			environment.getPropertySources().addFirst(new ResourcePropertySource(resource));
		}
	}
	catch (IOException e) {
		throw new IllegalStateException("Failed to add PropertySource to Environment", e);
	}
}
 
 类方法
 同包方法