public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); configurableEnvironment=environment; Properties props = new Properties(); String databaseMode = environment.getProperty("me.ramon.database-mode"); if (databaseMode != null) { if (databaseMode.equals("hibernate-multitenant")) { props.put("spring.jpa.properties.hibernate.multiTenancy", "DATABASE"); props.put("spring.jpa.properties.hibernate.tenant_identifier_resolver", "me.ramon.multitenancy.BaseCurrentTenantIdentifierResolverImp"); props.put("spring.jpa.properties.hibernate.multi_tenant_connection_provider", "me.ramon.multitenancy.BaseMultiTenantConnectionProviderImp"); } props.put("spring.jpa.hibernate.ddl-auto", "none"); props.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect"); props.put("hibernate.show_sql", "true"); props.put("logging.level.org.hibernate.SQL", "DEBUG"); props.put("logging.level.org.hibernate.type.descriptor.sql.BasicBinder", "TRACE"); props.put("spring.jpa.properties.hibernate.current_session_context_class", "org.springframework.orm.hibernate4.SpringSessionContext"); environment.getPropertySources().addLast(new PropertiesPropertySource("application1", props)); } }
@Override public PropertySource<?> locate(final Environment environment) { final AmazonDynamoDBClient amazonDynamoDBClient = getAmazonDynamoDbClient(environment); createSettingsTable(amazonDynamoDBClient, false); final ScanRequest scan = new ScanRequest(TABLE_NAME); LOGGER.debug("Scanning table with request [{}]", scan); final ScanResult result = amazonDynamoDBClient.scan(scan); LOGGER.debug("Scanned table with result [{}]", scan); final Properties props = new Properties(); result.getItems() .stream() .map(DynamoDbCloudConfigBootstrapConfiguration::retrieveSetting) .forEach(p -> props.put(p.getKey(), p.getValue())); return new PropertiesPropertySource(getClass().getSimpleName(), props); }
@Override public PropertySource<?> locate(final Environment environment) { final Properties props = new Properties(); try { final JdbcCloudConnection connection = new JdbcCloudConnection(environment); final DataSource dataSource = Beans.newDataSource(connection); final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); final List<Map<String, Object>> rows = jdbcTemplate.queryForList(connection.getSql()); for (final Map row : rows) { props.put(row.get("name"), row.get("value")); } } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return new PropertiesPropertySource(getClass().getSimpleName(), props); }
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { // 此处可以http方式 到配置服务器拉取一堆公共配置+本项目个性配置的json串,拼到Properties里 // ......省略new Properties的过程 MutablePropertySources propertySources = environment.getPropertySources(); // addLast 结合下面的 getOrder() 保证顺序 读者也可以试试其他姿势的加载顺序 try { Properties props = getConfig(environment); for (Object key : props.keySet()) { String keyStr = key.toString(); String value = props.getProperty(keyStr); if ("druid.writer.password,druid.reader.password".contains(keyStr)) { String dkey = props.getProperty("druid.key"); dkey = DataUtil.isEmpty(dkey) ? Constants.DB_KEY : dkey; value = SecurityUtil.decryptDes(value, dkey.getBytes()); props.setProperty(keyStr, value); } PropertiesUtil.getProperties().put(keyStr, value); } propertySources.addLast(new PropertiesPropertySource("thirdEnv", props)); } catch (IOException e) { logger.error("", e); } }
protected void mergePropertySource() throws Exception { if (this.environment != null) { this.addLast(new PropertySource<Environment>(PropertySourcesPlaceholderConfigurer.ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) { public String getProperty(String key) { return this.source.getProperty(key); } }); } else { logger.warn("The injected environment was null!"); } if (this.locations != null && this.locations.length > 0) { Properties localProperties = new Properties(); loadProperties(localProperties); PropertySource<?> localPropertySource = new PropertiesPropertySource(PropertySourcesPlaceholderConfigurer.LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, localProperties); if (this.localOverride) { this.addFirst(localPropertySource); } else { this.addLast(localPropertySource); } } }
@Test public void shouldUseAutoconfigurationToCreateMissingBeanWithCredentials() { ctx = new AnnotationConfigApplicationContext(); Properties properties = new Properties(); properties.setProperty("spring.hornetq.user", "user"); ctx.getEnvironment().getPropertySources().addFirst(new PropertiesPropertySource( "credentials", properties)); ctx.register(ClusteredHornetQAutoConfiguration.class); ctx.refresh(); UserCredentialsConnectionFactoryAdapter jmsConnectionFactory = (UserCredentialsConnectionFactoryAdapter) ctx .getBean("jmsConnectionFactory"); assertNotNull(jmsConnectionFactory); ConnectionFactory viaType = ctx.getBean(ConnectionFactory.class); assertSame(jmsConnectionFactory, viaType); }
@Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (CloudPlatform.CLOUD_FOUNDRY.isActive(environment)) { Properties properties = new Properties(); addWithPrefix(properties, getPropertiesFromApplication(environment), "vcap.application."); addWithPrefix(properties, getPropertiesFromServices(environment), "vcap.services."); MutablePropertySources propertySources = environment.getPropertySources(); if (propertySources.contains( CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) { propertySources.addAfter( CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME, new PropertiesPropertySource("vcap", properties)); } else { propertySources .addFirst(new PropertiesPropertySource("vcap", properties)); } } }
@Deprecated private Foo bindFoo(final String values) throws Exception { Properties properties = PropertiesLoaderUtils .loadProperties(new ByteArrayResource(values.getBytes())); if (this.usePropertySource) { MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new PropertiesPropertySource("test", properties)); this.factory.setPropertySources(propertySources); } else { this.factory.setProperties(properties); } this.factory.afterPropertiesSet(); return this.factory.getObject(); }
@Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { File home = getHomeFolder(); File propertyFile = (home == null ? null : new File(home, FILE_NAME)); if (propertyFile != null && propertyFile.exists() && propertyFile.isFile()) { FileSystemResource resource = new FileSystemResource(propertyFile); Properties properties; try { properties = PropertiesLoaderUtils.loadProperties(resource); environment.getPropertySources().addFirst( new PropertiesPropertySource("devtools-local", properties)); } catch (IOException ex) { throw new IllegalStateException("Unable to load " + FILE_NAME, ex); } } }
private AnnotationConfigApplicationContext context(Class<?>... clzz) throws Exception { AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(); annotationConfigApplicationContext.register(clzz); URL propertiesUrl = this.getClass().getClassLoader().getResource("config/application.properties"); File springBootPropertiesFile = new File(propertiesUrl.toURI()); Properties springBootProperties = new Properties(); springBootProperties.load(new FileInputStream(springBootPropertiesFile)); annotationConfigApplicationContext .getEnvironment() .getPropertySources() .addFirst(new PropertiesPropertySource("testProperties", springBootProperties)); annotationConfigApplicationContext.refresh(); return annotationConfigApplicationContext; }
/** * 刷新本地配置文件 */ private void refreshLocalFile() { Map<String, PropertySourcesPlaceholderConfigurer> placeholderMap = applicationContext.getBeansOfType( PropertySourcesPlaceholderConfigurer.class, true, false); if (!placeholderMap.isEmpty()) { for (Entry<String, PropertySourcesPlaceholderConfigurer> entry : placeholderMap.entrySet()) { PropertySourcesPlaceholderConfigurer placeholderConfigurer = entry.getValue(); Optional<PropertiesPropertySource> optional = PlaceholderResolved .getLocalPropertiesSources(placeholderConfigurer); if (MutablePropertySources.class.isAssignableFrom(placeholderConfigurer.getAppliedPropertySources() .getClass())) ((MutablePropertySources) placeholderConfigurer.getAppliedPropertySources()).replace( PropertySourcesEnum.LOCALPROPERTIES.getName(), optional.get()); } } }
/** * {@inheritDoc} * * <p> * Here we combine all properties, making sure that the Rice project properties go in last. * </p> */ @Override @Bean public PropertySource<?> propertySource() { List<Location> locations = Lists.newArrayList(); locations.addAll(jdbcConfig.jdbcPropertyLocations()); locations.addAll(sourceSqlConfig.riceSourceSqlPropertyLocations()); locations.addAll(ingestXmlConfig.riceIngestXmlPropertyLocations()); Properties properties = service.getProperties(locations); String location = ProjectUtils.getPath(RiceXmlProperties.APP.getResource()); Config riceConfig = RiceConfigUtils.parseAndInit(location); RiceConfigUtils.putProperties(riceConfig, properties); return new PropertiesPropertySource("properties", riceConfig.getProperties()); }
@Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { log.info("Detecting 'K8S'-Environment ..."); Properties properties = new Properties(); if (specificFilesystemLayoutExists()) { properties.put(K8S_ENABLED_KEY, Boolean.TRUE.toString()); properties.put(K8S_NAMESPACE, readNamespace()); log.info("'K8S'-metadata : {}", properties.toString()); } else { log.info("Ignore 'K8S', no metadata available."); properties.put(K8S_ENABLED_KEY, Boolean.FALSE.toString()); } // MutablePropertySources propertySources = environment.getPropertySources(); if (propertySources.contains(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) { propertySources.addAfter(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME, new PropertiesPropertySource(K8S_PREFIX, properties)); } else { propertySources.addFirst(new PropertiesPropertySource(K8S_PREFIX, properties)); } }
@Test public void testRepositoryNotInitialized() throws Exception { Properties properties = new Properties(); properties.put("spring.cloud.task.tablePrefix", "foobarless"); PropertiesPropertySource propertiesSource = new PropertiesPropertySource("test", properties); this.context = new AnnotationConfigApplicationContext(); this.context.getEnvironment().getPropertySources().addLast(propertiesSource); ((AnnotationConfigApplicationContext)context).register(SimpleTaskConfiguration.class); ((AnnotationConfigApplicationContext)context).register(PropertyPlaceholderAutoConfiguration.class); ((AnnotationConfigApplicationContext)context).register(EmbeddedDataSourceConfiguration.class); boolean wasExceptionThrown = false; try { this.context.refresh(); } catch (ApplicationContextException ex) { wasExceptionThrown = true; } assertTrue("Expected ApplicationContextException to be thrown", wasExceptionThrown); }
@Test public void shouldWrapExceptionOnEncryptionError() { // given StandardEnvironment environment = new StandardEnvironment(); Properties props = new Properties(); props.put("propertyDecryption.password", "NOT-A-PASSWORD"); props.put("someProperty", "{encrypted}NOT-ENCRYPTED"); environment.getPropertySources().addFirst(new PropertiesPropertySource("test-env", props)); exception.expect(RuntimeException.class); exception.expectMessage("Unable to decrypt property value '{encrypted}NOT-ENCRYPTED'"); exception.expectCause(isA(EncryptionOperationNotPossibleException.class)); ApplicationEnvironmentPreparedEvent event = new ApplicationEnvironmentPreparedEvent(new SpringApplication(), new String[0], environment); // when listener.onApplicationEvent(event); // then -> exception }
@Override public void initialize(ConfigurableWebApplicationContext ctx) { try { this.setLocations(ctx.getResources("/WEB-INF/application-customer-dev.properties")); Properties props = this.mergeProperties(); if (props.containsKey(TERRACOTTA_URL_KEY)) { System.setProperty(TERRACOTTA_URL_KEY, props.getProperty(TERRACOTTA_URL_KEY)); } ctx.getEnvironment().getPropertySources().addLast(new PropertiesPropertySource("default_properties", props)); this.setLocations(ctx.getResources("classpath:application-customer.properties")); props = this.mergeProperties(); if (props.containsKey(TERRACOTTA_URL_KEY)) { System.setProperty(TERRACOTTA_URL_KEY, props.getProperty(TERRACOTTA_URL_KEY)); } ctx.getEnvironment().getPropertySources() .addFirst(new PropertiesPropertySource("environment_properties", props)); } catch (IOException e) { logger.info("Unable to load properties file.", e); } }
@Override public void initialize(ConfigurableWebApplicationContext ctx) { try { this.setLocations(ctx.getResources("/WEB-INF/application-batch-dev.properties")); Properties props = this.mergeProperties(); if (props.containsKey(TERRACOTTA_URL_KEY)) { System.setProperty(TERRACOTTA_URL_KEY, props.getProperty(TERRACOTTA_URL_KEY)); } ctx.getEnvironment().getPropertySources().addLast(new PropertiesPropertySource("default_properties", props)); this.setLocations(ctx.getResources("classpath:application-batch.properties")); props = this.mergeProperties(); if (props.containsKey(TERRACOTTA_URL_KEY)) { System.setProperty(TERRACOTTA_URL_KEY, props.getProperty(TERRACOTTA_URL_KEY)); } ctx.getEnvironment().getPropertySources() .addFirst(new PropertiesPropertySource("environment_properties", props)); } catch (IOException e) { logger.info("Unable to load properties file.", e); } }
/** * Create Spring Bean factory. Parameter 'springContext' can be null. * * Create the Spring Bean Factory using the supplied <code>springContext</code>, * if not <code>null</code>. * * @param springContext Spring Context to create. If <code>null</code>, * use the default spring context. * The spring context is loaded as a spring ClassPathResource from * the class path. * * @return The Spring XML Bean Factory. * @throws BeansException If the Factory can not be created. * */ private ApplicationContext createApplicationContext() throws BeansException { // Reading in Spring Context long start = System.currentTimeMillis(); String springContext = "/springContext.xml"; ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(); MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources(); propertySources.remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME); propertySources.remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); propertySources.addFirst(new PropertiesPropertySource("ibis", APP_CONSTANTS)); applicationContext.setConfigLocation(springContext); applicationContext.refresh(); log("startup " + springContext + " in " + (System.currentTimeMillis() - start) + " ms"); return applicationContext; }
@Before public void setUp() { Properties props = new Properties(); props.put("mongoCollection", COLLECTION_BM_USER_DATA_SERVICE); ctx = new ClassPathXmlApplicationContext(new String[] { "test-MongoUserDataTest-context.xml" }, false); ctx.getEnvironment().getPropertySources().addFirst(new PropertiesPropertySource("TestProps", props)); ctx.refresh(); ctx.start(); userDataService = ctx.getBean(UserDataService.class); // Generate some random users for (int i = 0; i < UserDataServiceTest.USERS.length; i++) { String username = UserDataServiceTest.USERS[i]; UserData user = UserDataServiceTest.createUserData(username); userDataService.createNewUser(user); userDataService.setUserCreationState(username, DataCreationState.Created); } }
@Before public void setUp() { Properties props = new Properties(); props.put("mongoCollection", COLLECTION_BM_USER_DATA_SERVICE); ctx = new ClassPathXmlApplicationContext(new String[] {"test-MongoUserDataTest-context.xml"}, false); ctx.getEnvironment().getPropertySources().addFirst(new PropertiesPropertySource("TestProps", props)); ctx.refresh(); ctx.start(); userDataService = ctx.getBean(UserDataService.class); // Generate some random users for (int i = 0; i < USERS.length; i++) { String username = USERS[i]; UserData user = createUserData(username); userDataService.createNewUser(user); } }
@Test public void test_01() throws Exception { StandardEnvironment env = new StandardEnvironment(); java.util.Properties props = new java.util.Properties(); props.setProperty("spring.datasource.driverClassName", "com.mysql.jdbc.Driver"); props.setProperty("spring.datasource.url", "jdbc:mysql://localhost:3306/reqxldb?useUnicode=true"); props.setProperty("spring.datasource.username", "root"); props.setProperty("spring.datasource.password", "1234"); props.setProperty("spring.datasource.nrOfPoolConnections", "10"); env.getPropertySources().addFirst(new PropertiesPropertySource("test", props)); java.util.Properties from = NoJpaDatabaseProperties.from(env); Assert.assertEquals(from.getProperty("driverName"), "com.mysql.jdbc.Driver"); Assert.assertEquals(from.getProperty("user"), "root"); Assert.assertEquals(from.getProperty("password"), "1234"); Assert.assertEquals(from.getProperty("nrOfPoolConnections"), "10"); Assert.assertEquals(from.getProperty("ip"), "localhost"); Assert.assertEquals(from.getProperty("database"), "mysql"); Assert.assertEquals(from.getProperty("databaseName"), "reqxldb?useUnicode=true"); Assert.assertEquals(from.getProperty("port"), "3306"); }
@Test public void test() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); Properties properties = new Properties(); properties.put("prefix","foo"); properties.put("suffix","bar"); context.getEnvironment().getPropertySources().addLast(new PropertiesPropertySource("options", properties)); context.register(TestConfiguration.class); context.refresh(); MessageChannel input = context.getBean("input", MessageChannel.class); SubscribableChannel output = context.getBean("output", SubscribableChannel.class); final AtomicBoolean handled = new AtomicBoolean(); output.subscribe(new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { handled.set(true); assertEquals("foohellobar", message.getPayload()); } }); input.send(new GenericMessage<String>("hello")); assertTrue(handled.get()); }
/** * Init. */ @PostConstruct public void init() { final Properties sysProps = System.getProperties(); final Properties properties = new Properties(); if (CasVersion.getVersion() != null) { properties.put("info.cas.version", CasVersion.getVersion()); } properties.put("info.cas.date", CasVersion.getDateTime()); properties.put("info.cas.java.home", sysProps.get("java.home")); properties.put("info.cas.java.vendor", sysProps.get("java.vendor")); properties.put("info.cas.java.version", sysProps.get("java.version")); final PropertiesPropertySource src = new PropertiesPropertySource(CasVersion.class.getName(), properties); this.environment.getPropertySources().addFirst(src); }
@Override public PropertySource<?> locate(final Environment environment) { this.configurationJasyptDecryptor = new CasConfigurationJasyptDecryptor(environment); final Properties props = new Properties(); loadEmbeddedYamlOverriddenProperties(props, environment); final File configFile = configurationPropertiesEnvironmentManager().getStandaloneProfileConfigurationFile(); if (configFile != null) { loadSettingsFromStandaloneConfigFile(props, configFile); } final File config = configurationPropertiesEnvironmentManager().getStandaloneProfileConfigurationDirectory(); LOGGER.debug("Located CAS standalone configuration directory at [{}]", config); if (config.isDirectory() && config.exists()) { loadSettingsFromConfigurationSources(environment, props, config); } else { LOGGER.warn("Configuration directory [{}] is not a directory or cannot be found at the specific path", config); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Located setting(s) [{}] from [{}]", props.keySet(), config); } else { LOGGER.info("Found and loaded [{}] setting(s) from [{}]", props.size(), config); } return new PropertiesPropertySource("standaloneCasConfigService", props); }
@Bean(name = "dbSource") public PropertiesPropertySource[] source( @Named("dbProps") OrderedProperties orderedProperties, ConfigurableEnvironment environment) throws Exception { PropertiesPropertySource[] propertiesPropertySources = orderedProperties.toPropertiesPropertySources(); for(int i=(propertiesPropertySources.length-1);i>=0;i--){ environment.getPropertySources().addFirst(propertiesPropertySources[i]); } return propertiesPropertySources; }
/** * Creates an array of {@link PropertiesPropertySource} with respect to the insertion-order of the backing properties map. * This allows to add the returned {@link PropertiesPropertySource} instances to your environment maintaining the correct hierarchy (e.g. most specific to general properties). * * @return an array of {@link PropertiesPropertySource} */ public PropertiesPropertySource[] toPropertiesPropertySources(){ List<PropertiesPropertySource> propertiesPropertySources = new ArrayList<>(); List<String> keySet = this.getKeys(); for(String key: keySet){ propertiesPropertySources.add(new PropertiesPropertySource(key, this.properties.get(key))); } return propertiesPropertySources.toArray(new PropertiesPropertySource[propertiesPropertySources.size()]); }
@Bean(name = "databaseConfigurationSources") public PropertiesPropertySource[] databaseConfigurationSources( @Named("daoConfigurationFactoryBean") OrderedProperties orderedProperties, ConfigurableEnvironment environment) throws Exception { PropertiesPropertySource[] propertiesPropertySources = orderedProperties.toPropertiesPropertySources(); for(int i=(propertiesPropertySources.length-1);i>=0;i--){ environment.getPropertySources().addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, propertiesPropertySources[i]); } return propertiesPropertySources; }
@Bean(name = "source") public PropertiesPropertySource[] source( @Qualifier("props") OrderedProperties orderedProperties, ConfigurableEnvironment environment) throws Exception { PropertiesPropertySource[] propertiesPropertySources = orderedProperties.toPropertiesPropertySources(); for(PropertiesPropertySource propertiesPropertySource: propertiesPropertySources){ environment.getPropertySources().addFirst(propertiesPropertySource); } return propertiesPropertySources; }
@Bean(name = "databaseConfigurationSources") public PropertiesPropertySource[] databaseConfigurationSource( @Named("databaseConfigurationFactoryBean") OrderedProperties orderedProperties, ConfigurableEnvironment environment) throws Exception { PropertiesPropertySource[] propertiesPropertySources = orderedProperties.toPropertiesPropertySources(); for(int i=(propertiesPropertySources.length-1);i>=0;i--){ environment.getPropertySources().addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, propertiesPropertySources[i]); } return propertiesPropertySources; }
@Bean(name = "source") public PropertiesPropertySource[] source( @Qualifier("props") OrderedProperties orderedProperties, ConfigurableEnvironment environment) throws Exception { PropertiesPropertySource[] propertiesPropertySources = orderedProperties.toPropertiesPropertySources(); for(PropertiesPropertySource propertiesPropertySource: propertiesPropertySources){ environment.getPropertySources().addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, propertiesPropertySource); } return propertiesPropertySources; }
/** * {@inheritDoc} * <p>Processing occurs by replacing ${...} placeholders in bean definitions by resolving each * against this configurer's set of {@link PropertySources}, which includes: * <ul> * <li>all {@linkplain org.springframework.core.env.ConfigurableEnvironment#getPropertySources * environment property sources}, if an {@code Environment} {@linkplain #setEnvironment is present} * <li>{@linkplain #mergeProperties merged local properties}, if {@linkplain #setLocation any} * {@linkplain #setLocations have} {@linkplain #setProperties been} * {@linkplain #setPropertiesArray specified} * <li>any property sources set by calling {@link #setPropertySources} * </ul> * <p>If {@link #setPropertySources} is called, <strong>environment and local properties will be * ignored</strong>. This method is designed to give the user fine-grained control over property * sources, and once set, the configurer makes no assumptions about adding additional sources. */ @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (this.propertySources == null) { this.propertySources = new MutablePropertySources(); if (this.environment != null) { this.propertySources.addLast( new PropertySource<Environment>(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) { @Override public String getProperty(String key) { return this.source.getProperty(key); } } ); } try { PropertySource<?> localPropertySource = new PropertiesPropertySource(LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, mergeProperties()); if (this.localOverride) { this.propertySources.addFirst(localPropertySource); } else { this.propertySources.addLast(localPropertySource); } } catch (IOException ex) { throw new BeanInitializationException("Could not load properties", ex); } } processProperties(beanFactory, new PropertySourcesPropertyResolver(this.propertySources)); this.appliedPropertySources = this.propertySources; }
@Override protected StorageComponent tryCompute() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); PropertiesPropertySource source = new PropertiesPropertySource("consumer", properties); context.getEnvironment().getPropertySources().addLast(source); context.register(PropertyPlaceholderAutoConfiguration.class); registerAutoConfiguration(context); context.refresh(); return context.getBean(StorageComponent.class); }
@PostConstruct public void printProperties() { log.info("**** APPLICATION PROPERTIES SOURCES ****"); Set<String> properties = new TreeSet<>(); for (PropertiesPropertySource p : findPropertiesPropertySources()) { log.info(p.toString()); properties.addAll(Arrays.asList(p.getPropertyNames())); } log.info("**** APPLICATION PROPERTIES VALUES ****"); print(properties); }
private List<PropertiesPropertySource> findPropertiesPropertySources() { List<PropertiesPropertySource> propertiesPropertySources = new LinkedList<>(); for (PropertySource<?> propertySource : environment.getPropertySources()) { if (propertySource instanceof PropertiesPropertySource) { propertiesPropertySources.add((PropertiesPropertySource) propertySource); } } return propertiesPropertySources; }