下面列出了怎么用org.springframework.context.support.PropertySourcesPlaceholderConfigurer的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testMethodHavingNameFromPropertyFile() {
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton("messageHandler", MessageHandlersWithProperty.class);
applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.class);
Map<String, Object> map = new HashMap<>();
map.put("slow.queue.name", slowQueue);
map.put("smart.queue.name", smartQueue);
applicationContext
.getEnvironment()
.getPropertySources()
.addLast(new MapPropertySource("test", map));
applicationContext.registerSingleton("ppc", PropertySourcesPlaceholderConfigurer.class);
applicationContext.refresh();
MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class);
MessageHandlersWithProperty messageListener =
applicationContext.getBean(MessageHandlersWithProperty.class);
messageHandler.handleMessage(buildMessage(slowQueue, message));
assertEquals(message, messageListener.getLastReceivedMessage());
messageListener.setLastReceivedMessage(null);
messageHandler.handleMessage(buildMessage(smartQueue, message + message));
assertEquals(message + message, messageListener.getLastReceivedMessage());
}
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
AnnotationAttributes attributes = AnnotationAttributes
.fromMap(importingClassMetadata.getAnnotationAttributes(EnableApolloConfig.class.getName()));
String[] namespaces = attributes.getStringArray("value");
int order = attributes.getNumber("order");
PropertySourcesProcessor.addNamespaces(Lists.newArrayList(namespaces), order);
Map<String, Object> propertySourcesPlaceholderPropertyValues = new HashMap<>();
// to make sure the default PropertySourcesPlaceholderConfigurer's priority is higher than PropertyPlaceholderConfigurer
propertySourcesPlaceholderPropertyValues.put("order", 0);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesPlaceholderConfigurer.class.getName(),
PropertySourcesPlaceholderConfigurer.class, propertySourcesPlaceholderPropertyValues);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesProcessor.class.getName(),
PropertySourcesProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, ApolloAnnotationProcessor.class.getName(),
ApolloAnnotationProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueProcessor.class.getName(),
SpringValueProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueDefinitionProcessor.class.getName(),
SpringValueDefinitionProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, ApolloJsonValueProcessor.class.getName(),
ApolloJsonValueProcessor.class);
}
@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
configurer.setIgnoreResourceNotFound(true);
configurer.setIgnoreUnresolvablePlaceholders(true);
MutablePropertySources propertySources = new MutablePropertySources();
MockPropertySource source = new MockPropertySource()
.withProperty("rabbitmq.host", "192.168.10.10")
.withProperty("rabbitmq.port", "5673")
.withProperty("rabbitmq.username", "jfw")
.withProperty("rabbitmq.password", "jfw")
.withProperty("rabbitmq.channel-cache-size", 100);
propertySources.addLast(source);
configurer.setPropertySources(propertySources);
return configurer;
}
/**
* Make vars.properties available to spring integration configuration
* System properties are only used if there is no setting in vars.properties.
*/
@Bean(name = "aemServiceConfigurationPropertiesConfigurer")
public static PropertySourcesPlaceholderConfigurer configurer() {
PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
ppc.setLocation(new ClassPathResource("META-INF/spring/jwala-defaults.properties"));
ppc.setLocalOverride(true);
ppc.setProperties(ApplicationProperties.getProperties());
return ppc;
}
private PropertySourcesPlaceholderConfigurer getSinglePropertySourcesPlaceholderConfigurer(DefaultListableBeanFactory beanFactory) {
if (beanFactory instanceof ListableBeanFactory) {
ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
Map<String, PropertySourcesPlaceholderConfigurer> beans = listableBeanFactory
.getBeansOfType(PropertySourcesPlaceholderConfigurer.class, false,
false);
if (beans.size() == 1) {
return beans.values().iterator().next();
}
}
return null;
}
private void propertyPlaceholderWithFixedRate(boolean durationFormat) {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertySourcesPlaceholderConfigurer.class);
Properties properties = new Properties();
properties.setProperty("fixedRate", (durationFormat ? "PT3S" : "3000"));
properties.setProperty("initialDelay", (durationFormat ? "PT1S" : "1000"));
placeholderDefinition.getPropertyValues().addPropertyValue("properties", properties);
BeanDefinition targetDefinition = new RootBeanDefinition(PropertyPlaceholderWithFixedRateTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
context.registerBeanDefinition("placeholder", placeholderDefinition);
context.registerBeanDefinition("target", targetDefinition);
context.refresh();
ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class);
assertEquals(1, postProcessor.getScheduledTasks().size());
Object target = context.getBean("target");
ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
@SuppressWarnings("unchecked")
List<IntervalTask> fixedRateTasks = (List<IntervalTask>)
new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks");
assertEquals(1, fixedRateTasks.size());
IntervalTask task = fixedRateTasks.get(0);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
Object targetObject = runnable.getTarget();
Method targetMethod = runnable.getMethod();
assertEquals(target, targetObject);
assertEquals("fixedRate", targetMethod.getName());
assertEquals(1000L, task.getInitialDelay());
assertEquals(3000L, task.getInterval());
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() throws IOException {
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
pspc.setIgnoreResourceNotFound(true);
pspc.setIgnoreUnresolvablePlaceholders(true);
return pspc;
}
@Bean
public static PropertySourcesPlaceholderConfigurer properties(@Qualifier("graviteeProperties") Properties graviteeProperties) {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
propertySourcesPlaceholderConfigurer.setProperties(graviteeProperties);
propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
return propertySourcesPlaceholderConfigurer;
}
@Test
public void spr12233() throws Exception {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(PropertySourcesPlaceholderConfigurer.class);
ctx.register(ImportConfiguration.class);
ctx.refresh();
ctx.close();
}
@Bean
@Profile(Profiles.TEST)
public static PropertySourcesPlaceholderConfigurer testProperties() {
return createPropertySourcesPlaceholderConfigurer(
"common_application.properties",
"common_test_application.properties");
}
@ConditionalOnMissingBean(name = "propertySourcesPlaceholderConfigurer")
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() throws IOException {
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
pspc.setIgnoreResourceNotFound(true);
pspc.setIgnoreUnresolvablePlaceholders(true);
return pspc;
}
private List<PropertySourcesPlaceholderConfigurer> getAllPropertySourcesPlaceholderConfigurers() {
if (!(this.beanFactory instanceof ListableBeanFactory)) {
return emptyList();
}
ListableBeanFactory listableBeanFactory = (ListableBeanFactory) this.beanFactory;
// take care not to cause early instantiation of flattenedPropertySources FactoryBeans
Map<String, PropertySourcesPlaceholderConfigurer> beans = listableBeanFactory
.getBeansOfType(PropertySourcesPlaceholderConfigurer.class, false, false);
List<PropertySourcesPlaceholderConfigurer> configurers = new ArrayList<>(beans.values());
configurers.sort(comparingInt(PropertyResourceConfigurer::getOrder));
return configurers;
}
@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
configurer.setIgnoreResourceNotFound(true);
configurer.setIgnoreUnresolvablePlaceholders(true);
MutablePropertySources propertySources = new MutablePropertySources();
MockPropertySource source = new MockPropertySource()
.withProperty("rabbitmq.port", "invalid");
propertySources.addLast(source);
configurer.setPropertySources(propertySources);
return configurer;
}
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new ClassPathResource(CLIENT_PROPERTY_FILE));
propertySourcesPlaceholderConfigurer.setProperties(Objects.requireNonNull(yaml.getObject()));
return propertySourcesPlaceholderConfigurer;
}
@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
configurer.setIgnoreResourceNotFound(true);
configurer.setIgnoreUnresolvablePlaceholders(true);
return configurer;
}
private PropertySourcesPlaceholderConfigurer getSinglePropertySourcesPlaceholderConfigurer() {
// Take care not to cause early instantiation of all FactoryBeans
Map<String, PropertySourcesPlaceholderConfigurer> beans = this.applicationContext
.getBeansOfType(PropertySourcesPlaceholderConfigurer.class, false, false);
if (beans.size() == 1) {
return beans.values().iterator().next();
}
if (beans.size() > 1 && logger.isWarnEnabled()) {
logger.warn(
"Multiple PropertySourcesPlaceholderConfigurer " + "beans registered "
+ beans.keySet() + ", falling back to Environment");
}
return null;
}
@Bean
@Profile(Profiles.PROD)
public static PropertySourcesPlaceholderConfigurer prodProperties() {
return createPropertySourcesPlaceholderConfigurer(
"common_application.properties",
"common_prod_application.properties");
}
@Override
protected Class<?> getBeanClass(Element element) {
// As of Spring 3.1, the default value of system-properties-mode has changed from
// 'FALLBACK' to 'ENVIRONMENT'. This latter value indicates that resolution of
// placeholders against system properties is a function of the Environment and
// its current set of PropertySources.
if (SYSTEM_PROPERTIES_MODE_DEFAULT.equals(element.getAttribute(SYSTEM_PROPERTIES_MODE_ATTRIBUTE))) {
return PropertySourcesPlaceholderConfigurer.class;
}
// The user has explicitly specified a value for system-properties-mode: revert to
// PropertyPlaceholderConfigurer to ensure backward compatibility with 3.0 and earlier.
return PropertyPlaceholderConfigurer.class;
}
@Test
public void testProtobufMessagesSchema() throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("admin.enabled", "true");
properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort());
properties.put("admin.hostname", "localhost");
properties.put("websocket.enabled", "true");
properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
properties.put("websocket.hostname", "localhost");
properties.put("http.enabled", "false");
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
StandardEnvironment environment = new StandardEnvironment();
environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
context.setEnvironment(environment);
context.register(PropertySourcesPlaceholderConfigurer.class);
context.register(TransportConfiguration.class);
RestTemplate httpClient = new RestTemplate();
try {
context.refresh();
httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
ResponseEntity<String> response = httpClient.getForEntity(
new URI("http://localhost:" + properties.get("admin.port") + "/schema/messages/protobuf"), String.class);
logger.info("Got response: [{}]", response);
Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
Assert.assertTrue(response.getBody().contains("message error"));
} finally {
context.close();
}
}
@Bean
public static PropertySourcesPlaceholderConfigurer properties(@Qualifier("graviteeProperties") Properties graviteeProperties) {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
propertySourcesPlaceholderConfigurer.setProperties(graviteeProperties);
propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
return propertySourcesPlaceholderConfigurer;
}
@Test
public void testProtobufMessagesEnvelope() throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("admin.enabled", "true");
properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort());
properties.put("admin.hostname", "localhost");
properties.put("websocket.enabled", "true");
properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
properties.put("websocket.hostname", "localhost");
properties.put("http.enabled", "false");
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
StandardEnvironment environment = new StandardEnvironment();
environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
context.setEnvironment(environment);
context.register(PropertySourcesPlaceholderConfigurer.class);
context.register(TransportConfiguration.class);
RestTemplate httpClient = new RestTemplate();
try {
context.refresh();
httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
ResponseEntity<String> response = httpClient.getForEntity(
new URI("http://localhost:" + properties.get("admin.port") + "/schema/envelope/protobuf"), String.class);
logger.info("Got response: [{}]", response);
Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
Assert.assertTrue(response.getBody().contains("message Envelope"));
} finally {
context.close();
}
}
@Test
public void testEmptyWebSocketFrameUsingText() throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("websocket.enabled", "true");
properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
properties.put("websocket.hostname", "localhost");
properties.put("http.enabled", "false");
properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
properties.put("http.hostname", "localhost");
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
StandardEnvironment environment = new StandardEnvironment();
environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
context.setEnvironment(environment);
context.register(PropertySourcesPlaceholderConfigurer.class);
context.register(TransportConfiguration.class);
context.register(TestWebSocketService.class);
WebSocketClient wsClient = new WebSocketClient();
try {
//start server
context.refresh();
// start client
wsClient.start();
final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);
final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);
QueuingWebSocketListener listener = new QueuingWebSocketListener(serDe, messageRegistry, null);
WebSocketSession session = (WebSocketSession)wsClient.connect(listener, new URI("ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName()))
.get(5000, TimeUnit.MILLISECONDS);
session.getRemote().sendString("");
ServiceError error = listener.getResponse(5, TimeUnit.SECONDS);
Assert.assertNotNull(error);
Assert.assertEquals("EMPTY_ENVELOPE", error.code);
Assert.assertEquals("STOPPED", session.getState());
} finally {
try {
wsClient.stop();
} finally {
context.close();
}
}
}
@Bean
public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public PropertySourcesPlaceholderConfigurer ppc() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public static PropertySourcesPlaceholderConfigurer ppc() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
propertyPlaceholderConfigurer.setLocation(new ClassPathResource("nextrtc.properties"));
return propertyPlaceholderConfigurer;
}
@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
PropertySourcesPlaceholderConfigurer props = new PropertySourcesPlaceholderConfigurer();
props.setNullValue("");
return props;
}