下面列出了怎么用org.springframework.core.env.PropertiesPropertySource的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
new TransactionManagerCustomizer().apply(environment);
if (environment.getProperty(METRICS_INFLUX_ENABLED) == null) {
logger.info("{} not set. Default enable", METRICS_INFLUX_ENABLED);
Properties props = createProperties(environment);
logger.info("summerframeworkMicrometer = {}", props);
environment.getPropertySources().addLast(new PropertiesPropertySource("summerframeworkMicrometer", props));
}
}
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
String functionName = environment.containsProperty("function.name") ? environment.getProperty("function.name") : null;
String functionLocation = environment.containsProperty("function.location") ? environment.getProperty("function.location") : null;
if (StringUtils.hasText(functionName) || StringUtils.hasText(functionLocation)) {
MutablePropertySources propertySources = environment.getPropertySources();
propertySources.forEach(ps -> {
if (ps instanceof PropertiesPropertySource) {
((MapPropertySource) ps).getSource().put(FunctionProperties.PREFIX + ".definition", functionName);
((MapPropertySource) ps).getSource().put(FunctionProperties.PREFIX + ".location", functionLocation);
}
});
}
}
@Before
@SuppressWarnings("resource")
public void setup() {
StaticWebApplicationContext wac = new StaticWebApplicationContext();
Properties props = new Properties();
props.setProperty("myOrigin", "https://example.com");
wac.getEnvironment().getPropertySources().addFirst(new PropertiesPropertySource("ps", props));
wac.registerSingleton("ppc", PropertySourcesPlaceholderConfigurer.class);
wac.refresh();
this.handlerMapping.setRemoveSemicolonContent(false);
wac.getAutowireCapableBeanFactory().initializeBean(this.handlerMapping, "hm");
this.request.setMethod("GET");
this.request.addHeader(HttpHeaders.ORIGIN, "https://domain.com/");
}
/**
* 从外部获取配置文件,并对加密后的数据库用户名和密码做解密
*
* @param environment
* @param application
*/
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
String configPath = environment.getProperty("path");
if (Env.getCurrentEnv() == LOCAL) {
eagerLoad(environment);
return;
}
File file = new File(defaultIfBlank(configPath, "/opt/sqcs_backend/spring.properties"));
log.info("configPath:{}", configPath);
try (InputStream input = new FileInputStream(file)) {
Properties properties = buildDecryptProperties(input);
PropertiesPropertySource propertySource = new PropertiesPropertySource("spring", properties);
environment.getPropertySources().addLast(propertySource);
} catch (Exception e) {
throw new SeppServerException("配置文件读取错误", e);
}
}
@Override
protected WebApplicationContext createWebApplicationContext(ServletContext servletContext) {
System.setProperty(EndpointImpl.CHECK_PUBLISH_ENDPOINT_PERMISSON_PROPERTY_WITH_SECURITY_MANAGER, "false");
servletContext.log("Starting IBIS WebApplicationInitializer");
XmlWebApplicationContext applicationContext = new XmlWebApplicationContext();
applicationContext.setConfigLocation(XmlWebApplicationContext.CLASSPATH_URL_PREFIX + "/webApplicationContext.xml");
applicationContext.setDisplayName("IbisApplicationInitializer");
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", AppConstants.getInstance()));
return applicationContext;
}
@Before
@SuppressWarnings("resource")
public void setup() {
StaticWebApplicationContext wac = new StaticWebApplicationContext();
Properties props = new Properties();
props.setProperty("myOrigin", "http://example.com");
wac.getEnvironment().getPropertySources().addFirst(new PropertiesPropertySource("ps", props));
wac.registerSingleton("ppc", PropertySourcesPlaceholderConfigurer.class);
wac.refresh();
this.handlerMapping.setRemoveSemicolonContent(false);
wac.getAutowireCapableBeanFactory().initializeBean(this.handlerMapping, "hm");
this.request.setMethod("GET");
this.request.addHeader(HttpHeaders.ORIGIN, "http://domain.com/");
}
protected void configureDispatcherServlet(DispatcherServlet dispatcherServlet) {
if (inheritGlobalProperties) {
final Properties globalProperties = (Properties) this.applicationContext.getBean("global-properties");
ConfigurableEnvironment servletEnv = dispatcherServlet.getEnvironment();
servletEnv.merge(new AbstractEnvironment() {
@Override
public MutablePropertySources getPropertySources() {
MutablePropertySources mutablePropertySources = new MutablePropertySources();
mutablePropertySources
.addFirst(new PropertiesPropertySource("alfresco-global.properties", globalProperties));
return mutablePropertySources;
}
});
}
}
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
Properties props = new Properties();
if (environment.containsProperty(MYBATIS_ENCRYPT_PASSWORD)) {
System.setProperty(MYBATIS_ENCRYPT_PASSWORD, environment.getProperty(MYBATIS_ENCRYPT_PASSWORD));
}
if (environment.containsProperty(MYBATIS_ENCRYPT_SALT)) {
System.setProperty(MYBATIS_ENCRYPT_SALT, environment.getProperty(MYBATIS_ENCRYPT_SALT));
}
if (environment.containsProperty(SHA1_COLUMN_HANDLER_SALT)) {
System.setProperty(SHA1_COLUMN_HANDLER_SALT, environment.getProperty(SHA1_COLUMN_HANDLER_SALT));
}
if (environment.containsProperty(MYBATIS_TYPE_HANDLERS_PACKAGE)) {
props.put(MYBATIS_TYPE_HANDLERS_PACKAGE,
environment.getProperty(MYBATIS_TYPE_HANDLERS_PACKAGE) + "," + MYBATIS_TYPE_HANDLERS_PACKAGE_VALUE);
} else {
props.put(MYBATIS_TYPE_HANDLERS_PACKAGE, MYBATIS_TYPE_HANDLERS_PACKAGE_VALUE);
}
environment.getPropertySources().addFirst(new PropertiesPropertySource("summerframeworkMybatis", props));
}
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
Properties props = new Properties();
if (!environment.containsProperty(ID_TYPE)) {
props.put(ID_TYPE, ID_TYPE_AUTO);
}
if (environment.containsProperty(MYBATIS_TYPE_HANDLERS_PACKAGE)) {
props.put(MYBATIS_TYPE_HANDLERS_PACKAGE,
environment.getProperty(MYBATIS_TYPE_HANDLERS_PACKAGE) + "," + MYBATIS_TYPE_HANDLERS_PACKAGE_VALUE);
} else {
props.put(MYBATIS_TYPE_HANDLERS_PACKAGE, MYBATIS_TYPE_HANDLERS_PACKAGE_VALUE);
}
environment.getPropertySources().addFirst(new PropertiesPropertySource("summerframeworkMybatisplus", props));
}
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
RemotePropertySource sources = event.getSpringApplication()
.getMainApplicationClass().getAnnotation(RemotePropertySource.class);
String configPath = Server.getInstance().getServerConfig().getBasePath() + "/conf/";
if (sources != null) {
for (String name : sources.value()) {
try {
ConfigHelper.getInstance().loadConfig(name);
File config = new File(configPath + name);
if (config.exists()) {
Properties properties = new Properties();
properties.load(new FileInputStream(config));
event.getEnvironment().getPropertySources().addFirst(new PropertiesPropertySource(name, properties));
} else {
throw new RuntimeException("[TARS] load config failed file not exists");
}
} catch (IOException e) {
System.err.println("[TARS] load config failed: " + name);
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws IOException {
// application.properties 文件资源 classpath 路径
String location = "application.properties";
// 编码化的 Resource 对象(解决乱码问题)
EncodedResource resource = new EncodedResource(new ClassPathResource(location), "UTF-8");
// 加载 application.properties 文件,转化为 Properties 对象
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
// 创建 Properties 类型的 PropertySource
PropertiesPropertySource propertySource = new PropertiesPropertySource("map", properties);
// 转化为 Spring Boot 2 外部化配置源 ConfigurationPropertySource 集合
Iterable<ConfigurationPropertySource> propertySources = ConfigurationPropertySources.from(propertySource);
// 创建 Spring Boot 2 Binder 对象(设置 ConversionService ,扩展类型转换能力)
Binder binder = new Binder(propertySources, null, conversionService());
// 执行绑定,返回绑定结果
BindResult<User> bindResult = binder.bind("user", User.class);
// 获取绑定对象
User user = bindResult.get();
// 输出结果
System.out.println(user);
}
@Override
public String[] selectImports(AnnotationMetadata metadata) {
String[] imports = super.selectImports(metadata);
Environment env = getEnvironment();
String grayEnabled = env.getProperty("gray.enabled");
if (StringUtils.isEmpty(grayEnabled)) {
if (ConfigurableEnvironment.class.isInstance(env)) {
ConfigurableEnvironment environment = (ConfigurableEnvironment) env;
MutablePropertySources m = environment.getPropertySources();
Properties p = new Properties();
p.put("gray.enabled", "true");
m.addLast(new PropertiesPropertySource("defaultProperties", p));
}
}
return imports;
}
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;
}
public PropertySource<?> load(String name, Resource resource, String profile) throws IOException {
logger.info("load PropertySource -> name:{},profile:{}", name, profile);
if (profile == null) {
Properties properties = loadProperties(name,resource);
if (profiles == null) {
profiles = properties.getProperty("spring.profiles.active");
} else {
logger.info("spring.profiles.active = " + profiles + ",ignore load remote config");
}
// 如果指定了profile,则也不加载远程配置
if (profiles == null && ccContext.isRemoteEnabled() && !ccContext.isProcessed()) {
ccContext.init(properties, true);
ccContext.mergeRemoteProperties(properties);
}
if (!properties.isEmpty()) {
return new PropertiesPropertySource(name, properties);
}
}
return null;
}
public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
Properties properties = loadProperties(name,resource);
if (profiles == null) {
profiles = properties.getProperty("spring.profiles.active");
} else {
logger.info("spring.profiles.active = " + profiles + ",ignore load remote config");
}
// 如果指定了profile,则也不加载远程配置
if (profiles == null && ccContext.isRemoteEnabled() && !ccContext.isProcessed()) {
ccContext.init(properties, true);
ccContext.mergeRemoteProperties(properties);
PropertySource<?> props = new PropertiesPropertySource(ConfigcenterContext.MANAGER_PROPERTY_SOURCE, properties);
return Arrays.asList(props);
}
return new ArrayList<>();
}
@Test
void properties_set_shouldOverrideValues() {
Properties properties = new Properties();
properties.setProperty("management.metrics.export.cloudwatch.namespace", "test");
properties.setProperty("management.metrics.export.cloudwatch.batch-size", "5");
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.getEnvironment().getPropertySources()
.addLast(new PropertiesPropertySource("test", properties));
applicationContext.register(CloudWatchPropertiesConfiguration.class);
applicationContext.refresh();
CloudWatchProperties cloudWatchProperties = applicationContext
.getBean(CloudWatchProperties.class);
assertThat(cloudWatchProperties.getNamespace()).isEqualTo("test");
assertThat(cloudWatchProperties.getBatchSize()).isEqualTo(5);
}
/**
* {@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());
}
/**
* 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
@Nullable
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 ApplicationContext initApplicationContext() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(WebConfig.class);
Properties props = new Properties();
props.setProperty("myOrigin", "https://site1.com");
context.getEnvironment().getPropertySources().addFirst(new PropertiesPropertySource("ps", props));
context.register(PropertySourcesPlaceholderConfigurer.class);
context.refresh();
return context;
}
@Bean
@Lazy(false)
public MutablePropertySources springBootPropertySource() {
MutablePropertySources sources = env.getPropertySources();
sources.addFirst(new PropertiesPropertySource("boot-test-property", CamelCloudServiceCallRefExpressionTest.getAllProperties()));
return sources;
}
@Bean
@Lazy(false)
public MutablePropertySources springBootPropertySource() {
MutablePropertySources sources = env.getPropertySources();
sources.addFirst(new PropertiesPropertySource("boot-test-property", CamelCloudServiceCallSimpleExpressionTest.getAllProperties()));
return sources;
}
@Bean
@Lazy(false)
public MutablePropertySources springBootPropertySource() {
MutablePropertySources sources = env.getPropertySources();
sources.addFirst(new PropertiesPropertySource("boot-test-property", CamelCloudServiceCallTest.getAllProperties()));
return sources;
}
@Bean
@Lazy(false)
public MutablePropertySources springBootPropertySource() {
MutablePropertySources sources = env.getPropertySources();
sources.addFirst(new PropertiesPropertySource("boot-test-property", CamelCloudServiceCallGlobalConfigurationTest.getAllProperties()));
return sources;
}
protected void initialize(ConfigurableEnvironment environment) throws IOException {
String resolvedLocation = environment.resolveRequiredPlaceholders("classpath:spring.properties");
Resource resource = this.resourceLoader.getResource(resolvedLocation);
Properties properties = new Properties();
properties.load(resource.getInputStream());
String logPath = properties.getProperty(SEPP_LOG_PATH);
if (StringUtils.isNotBlank(logPath)) {
Properties logProperties = new Properties();
logProperties.setProperty(SEPP_LOG_PATH, logPath);
PropertiesPropertySource propertySource = new PropertiesPropertySource(UUID.randomUUID().toString(), logProperties);
environment.getPropertySources().addLast(propertySource);
}
}
@Override
public void customize(ConfigurableEnvironment env) {
try {
Properties props;
ClassPathResource resource = new ClassPathResource(DEFAULT_PROPERTY);
props = PropertiesLoaderUtils.loadProperties(resource);
props.put(SPRINGBOOT_MANAGEMENT_PORT_KEY, getManagementPort(env));
env.getPropertySources().addLast(new PropertiesPropertySource("managementProperties", props));
} catch (IOException e) {
logger.error("Failed to load " + DEFAULT_PROPERTY);
}
}
@Override
public void customize(ConfigurableEnvironment env) {
try {
Properties props;
ClassPathResource resource = new ClassPathResource(DEFAULT_PROPERTY);
props = PropertiesLoaderUtils.loadProperties(resource);
props.put(SPRINGBOOT_MANAGEMENT_PORT_KEY, getManagementPort(env));
env.getPropertySources().addLast(new PropertiesPropertySource("managementProperties", props));
} catch (IOException e) {
logger.error("Failed to load " + DEFAULT_PROPERTY);
}
}
public void initialize(ConfigurableApplicationContext context) {
val propertySources = context.getEnvironment().getPropertySources();
propertySources.addLast(new ConfigurationPropertySource(plugin.getConfig()));
val props = new Properties();
props.put("spigot.plugin", plugin.getName());
propertySources.addLast(new PropertiesPropertySource("spring-bukkit", props));
}
@Test
public void shouldRegisterHookProperties() {
initializer.initialize(context);
verify(propertySources, times(2)).addLast(propertySourceCaptor.capture());
PropertiesPropertySource propertySource = propertySourceCaptor.getValue();
Map<String, Object> props = propertySource.getSource();
assertEquals(PLUGIN_NAME, props.get("spigot.plugin"));
}
@Override
public PropertySource<?> locate(Environment environment) {
String jwtToken = environment.getProperty("rsocket.jwt-token");
String rsocketBrokers = environment.getProperty("rsocket.brokers");
String applicationName = environment.getProperty("spring.application.name");
if (CONFIG_SOURCES.containsKey(applicationName)) {
return CONFIG_SOURCES.get(applicationName);
}
if (jwtToken != null && rsocketBrokers != null && applicationName != null) {
Properties configProperties = new Properties();
for (String rsocketBroker : rsocketBrokers.split(",")) {
URI rsocketURI = URI.create(rsocketBroker);
String httpUri = "http://" + rsocketURI.getHost() + ":" + (rsocketURI.getPort() - 1) + "/config/last/" + applicationName;
try {
String configText = WebClient.create().get()
.uri(httpUri)
.header(HttpHeaders.AUTHORIZATION, "Bearer " + jwtToken)
.retrieve()
.bodyToMono(String.class)
.block();
if (configText != null && !configText.isEmpty()) {
LAST_CONFIG_TEXT = configText;
configProperties.load(new StringReader(LAST_CONFIG_TEXT));
CONFIG_PROPERTIES.put(applicationName, configProperties);
log.info(RsocketErrorCode.message("RST-202200", applicationName));
} else {
log.info(RsocketErrorCode.message("RST-202404", applicationName));
}
configProperties.setProperty("rsocket.metadata.config", "true");
PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource("rsocket-broker", configProperties);
CONFIG_SOURCES.put(applicationName, propertiesPropertySource);
return propertiesPropertySource;
} catch (Exception e) {
log.error(RsocketErrorCode.message("RST-202500", httpUri), e);
}
}
}
log.error(RsocketErrorCode.message("RST-202201"));
throw new RuntimeException(RsocketErrorCode.message("RST-202201"));
}
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ConfigurableEnvironment environment = event.getEnvironment();
Properties props = new Properties();
props.put("server.servlet.register-default-servlet", "false");
props.put("spring.aop.proxy-target-class", "false");
environment.getPropertySources().addFirst(new PropertiesPropertySource("native", props));
}