下面列出了怎么用org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void configurationWithPostProcessor() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ConfigWithPostProcessor.class);
RootBeanDefinition placeholderConfigurer = new RootBeanDefinition(PropertyPlaceholderConfigurer.class);
placeholderConfigurer.getPropertyValues().add("properties", "myProp=myValue");
ctx.registerBeanDefinition("placeholderConfigurer", placeholderConfigurer);
ctx.refresh();
TestBean foo = ctx.getBean("foo", TestBean.class);
ITestBean bar = ctx.getBean("bar", ITestBean.class);
ITestBean baz = ctx.getBean("baz", ITestBean.class);
assertEquals("foo-processed-myValue", foo.getName());
assertEquals("bar-processed-myValue", bar.getName());
assertEquals("baz-processed-myValue", baz.getName());
SpousyTestBean listener = ctx.getBean("listenerTestBean", SpousyTestBean.class);
assertTrue(listener.refreshed);
ctx.close();
}
@Test
@SuppressWarnings("resource")
public void formatFieldForValueInjectionUsingMetaAnnotations() {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
RootBeanDefinition bd = new RootBeanDefinition(MetaValueBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
ac.registerBeanDefinition("valueBean", bd);
ac.registerBeanDefinition("conversionService", new RootBeanDefinition(FormattingConversionServiceFactoryBean.class));
ac.registerBeanDefinition("ppc", new RootBeanDefinition(PropertyPlaceholderConfigurer.class));
ac.refresh();
System.setProperty("myDate", "10-31-09");
System.setProperty("myNumber", "99.99%");
try {
MetaValueBean valueBean = ac.getBean(MetaValueBean.class);
assertEquals(new LocalDate(2009, 10, 31), new LocalDate(valueBean.date));
assertEquals(Double.valueOf(0.9999), valueBean.number);
}
finally {
System.clearProperty("myDate");
System.clearProperty("myNumber");
}
}
@Test
public void propertyPlaceholderWithInactiveCron() {
String businessHoursCronExpression = "-";
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertyPlaceholderConfigurer.class);
Properties properties = new Properties();
properties.setProperty("schedules.businessHours", businessHoursCronExpression);
placeholderDefinition.getPropertyValues().addPropertyValue("properties", properties);
BeanDefinition targetDefinition = new RootBeanDefinition(PropertyPlaceholderWithCronTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
context.registerBeanDefinition("placeholder", placeholderDefinition);
context.registerBeanDefinition("target", targetDefinition);
context.refresh();
ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class);
assertTrue(postProcessor.getScheduledTasks().isEmpty());
}
@Test
public void testMultipleDefinedBeanFactoryPostProcessors() {
StaticApplicationContext ac = new StaticApplicationContext();
ac.registerSingleton("tb1", TestBean.class);
ac.registerSingleton("tb2", TestBean.class);
MutablePropertyValues pvs1 = new MutablePropertyValues();
pvs1.add("initValue", "${key}");
ac.registerSingleton("bfpp1", TestBeanFactoryPostProcessor.class, pvs1);
MutablePropertyValues pvs2 = new MutablePropertyValues();
pvs2.add("properties", "key=value");
ac.registerSingleton("bfpp2", PropertyPlaceholderConfigurer.class, pvs2);
ac.refresh();
TestBeanFactoryPostProcessor bfpp = (TestBeanFactoryPostProcessor) ac.getBean("bfpp1");
assertEquals("value", bfpp.initValue);
assertTrue(bfpp.wasCalled);
}
@Test
@SuppressWarnings("resource")
public void formatFieldForValueInjectionUsingMetaAnnotations() {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
RootBeanDefinition bd = new RootBeanDefinition(MetaValueBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
ac.registerBeanDefinition("valueBean", bd);
ac.registerBeanDefinition("conversionService", new RootBeanDefinition(FormattingConversionServiceFactoryBean.class));
ac.registerBeanDefinition("ppc", new RootBeanDefinition(PropertyPlaceholderConfigurer.class));
ac.refresh();
System.setProperty("myDate", "10-31-09");
System.setProperty("myNumber", "99.99%");
try {
MetaValueBean valueBean = ac.getBean(MetaValueBean.class);
assertEquals(new LocalDate(2009, 10, 31), new LocalDate(valueBean.date));
assertEquals(Double.valueOf(0.9999), valueBean.number);
}
finally {
System.clearProperty("myDate");
System.clearProperty("myNumber");
}
}
@Test
public void defaultExpressionParameters() throws Exception {
initServlet(wac -> {
RootBeanDefinition ppc = new RootBeanDefinition(PropertyPlaceholderConfigurer.class);
ppc.getPropertyValues().add("properties", "myKey=foo");
wac.registerBeanDefinition("ppc", ppc);
}, DefaultExpressionValueParamController.class);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myApp/myPath.do");
request.setContextPath("/myApp");
MockHttpServletResponse response = new MockHttpServletResponse();
System.setProperty("myHeader", "bar");
try {
getServlet().service(request, response);
}
finally {
System.clearProperty("myHeader");
}
assertEquals("foo-bar-/myApp", response.getContentAsString());
}
/**
* get {@link Properties} instance from {@link ConfigurableListableBeanFactory}.
*
* @param beanFactory spring container
* @return {@link Properties} instance
*/
public static Properties getRegisteredPropertyResourceConfigurer(
ConfigurableListableBeanFactory beanFactory) {
Class clazz = PropertyPlaceholderConfigurer.class;
Map beans = beanFactory.getBeansOfType(clazz);
if (beans == null || beans.isEmpty()) {
return null;
}
Object config = ((Map.Entry)beans.entrySet().iterator().next()).getValue();
if (clazz.isAssignableFrom(config.getClass())) {
Method m = ReflectionUtils.findMethod(clazz, "mergeProperties", new Class[0]);
if (m != null) {
m.setAccessible(true);
return (Properties) ReflectionUtils.invokeMethod(m, config);
}
}
return null;
}
@Override
protected void applyDefaultOverrides(PropertyBackedBeanState state) throws IOException
{
// Let the superclass propagate default settings from the global properties and register us
super.applyDefaultOverrides(state);
List<String> idList = getId();
// Apply any property overrides from the extension classpath and also allow system properties and JNDI to
// override. We use the type name and last component of the ID in the path
JndiPropertiesFactoryBean overrideFactory = new JndiPropertiesFactoryBean();
overrideFactory.setPropertiesPersister(getPersister());
overrideFactory.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
overrideFactory.setLocations(getParent().getResources(
ChildApplicationContextFactory.EXTENSION_CLASSPATH_PREFIX + getCategory() + '/' + getTypeName() + '/'
+ idList.get(idList.size() - 1) + ChildApplicationContextFactory.PROPERTIES_SUFFIX));
overrideFactory.setProperties(((ApplicationContextState) state).properties);
overrideFactory.afterPropertiesSet();
((ApplicationContextState) state).properties = (Properties) overrideFactory.getObject();
}
/**
* The Constructor.
*
* @param properties
* the properties
* @param compositeProperties
* the composite properties
* @throws BeansException
* the beans exception
*/
private ChildApplicationContext(Properties properties,
Map<String, Map<String, CompositeDataBean>> compositeProperties) throws BeansException
{
super(getContextResourcePatterns(), false, ChildApplicationContextFactory.this.getParent());
this.compositeProperties = compositeProperties;
// Add a property placeholder configurer, with the subsystem-scoped default properties
PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
configurer.setPropertiesArray(new Properties[] {ChildApplicationContextFactory.this.getPropertyDefaults(), properties});
configurer.setIgnoreUnresolvablePlaceholders(true);
configurer.setSearchSystemEnvironment(false);
addBeanFactoryPostProcessor(configurer);
setClassLoader(ChildApplicationContextFactory.this.getParent().getClassLoader());
}
@Test
public void configurationWithPostProcessor() {
AnnotationConfigApplicationContext factory = new AnnotationConfigApplicationContext();
factory.register(ConfigWithPostProcessor.class);
RootBeanDefinition placeholderConfigurer = new RootBeanDefinition(PropertyPlaceholderConfigurer.class);
placeholderConfigurer.getPropertyValues().add("properties", "myProp=myValue");
factory.registerBeanDefinition("placeholderConfigurer", placeholderConfigurer);
factory.refresh();
TestBean foo = factory.getBean("foo", TestBean.class);
ITestBean bar = factory.getBean("bar", ITestBean.class);
ITestBean baz = factory.getBean("baz", ITestBean.class);
assertEquals("foo-processed-myValue", foo.getName());
assertEquals("bar-processed-myValue", bar.getName());
assertEquals("baz-processed-myValue", baz.getName());
SpousyTestBean listener = factory.getBean("listenerTestBean", SpousyTestBean.class);
assertTrue(listener.refreshed);
}
@Test
public void testMultipleDefinedBeanFactoryPostProcessors() {
StaticApplicationContext ac = new StaticApplicationContext();
ac.registerSingleton("tb1", TestBean.class);
ac.registerSingleton("tb2", TestBean.class);
MutablePropertyValues pvs1 = new MutablePropertyValues();
pvs1.add("initValue", "${key}");
ac.registerSingleton("bfpp1", TestBeanFactoryPostProcessor.class, pvs1);
MutablePropertyValues pvs2 = new MutablePropertyValues();
pvs2.add("properties", "key=value");
ac.registerSingleton("bfpp2", PropertyPlaceholderConfigurer.class, pvs2);
ac.refresh();
TestBeanFactoryPostProcessor bfpp = (TestBeanFactoryPostProcessor) ac.getBean("bfpp1");
assertEquals("value", bfpp.initValue);
assertTrue(bfpp.wasCalled);
}
@Test
public void propertyPlaceholderSystemProperties() throws Exception {
String value = System.setProperty("foo", "spam");
try {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"contextNamespaceHandlerTests-system.xml", getClass());
Map<String, PropertyPlaceholderConfigurer> beans = applicationContext
.getBeansOfType(PropertyPlaceholderConfigurer.class);
assertFalse("No PropertyPlaceholderConfigurer found", beans.isEmpty());
assertEquals("spam", applicationContext.getBean("string"));
assertEquals("none", applicationContext.getBean("fallback"));
}
finally {
if (value != null) {
System.setProperty("foo", value);
}
}
}
@Test
@SuppressWarnings("resource")
public void testFormatFieldForValueInjectionUsingMetaAnnotations() {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
RootBeanDefinition bd = new RootBeanDefinition(MetaValueBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
ac.registerBeanDefinition("valueBean", bd);
ac.registerBeanDefinition("conversionService", new RootBeanDefinition(FormattingConversionServiceFactoryBean.class));
ac.registerBeanDefinition("ppc", new RootBeanDefinition(PropertyPlaceholderConfigurer.class));
ac.refresh();
System.setProperty("myDate", "10-31-09");
System.setProperty("myNumber", "99.99%");
try {
MetaValueBean valueBean = ac.getBean(MetaValueBean.class);
assertEquals(new LocalDate(2009, 10, 31), new LocalDate(valueBean.date));
assertEquals(Double.valueOf(0.9999), valueBean.number);
}
finally {
System.clearProperty("myDate");
System.clearProperty("myNumber");
}
}
@Test
public void defaultExpressionParameters() throws Exception {
initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
@Override
public void initialize(GenericWebApplicationContext context) {
RootBeanDefinition ppc = new RootBeanDefinition(PropertyPlaceholderConfigurer.class);
ppc.getPropertyValues().add("properties", "myKey=foo");
context.registerBeanDefinition("ppc", ppc);
}
}, DefaultExpressionValueParamController.class);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myApp/myPath.do");
request.setContextPath("/myApp");
MockHttpServletResponse response = new MockHttpServletResponse();
System.setProperty("myHeader", "bar");
try {
getServlet().service(request, response);
}
finally {
System.clearProperty("myHeader");
}
assertEquals("foo-bar-/myApp", response.getContentAsString());
}
public static AbstractEngineConfiguration parseEngineConfiguration(Resource springResource, String beanName) {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
xmlBeanDefinitionReader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
xmlBeanDefinitionReader.loadBeanDefinitions(springResource);
// Check non singleton beans for types
// Do not eagerly initialize FactorBeans when getting BeanFactoryPostProcessor beans
Collection<BeanFactoryPostProcessor> factoryPostProcessors = beanFactory.getBeansOfType(BeanFactoryPostProcessor.class, true, false).values();
if (factoryPostProcessors.isEmpty()) {
factoryPostProcessors = Collections.singleton(new PropertyPlaceholderConfigurer());
}
for (BeanFactoryPostProcessor factoryPostProcessor : factoryPostProcessors) {
factoryPostProcessor.postProcessBeanFactory(beanFactory);
}
AbstractEngineConfiguration engineConfiguration = (AbstractEngineConfiguration) beanFactory.getBean(beanName);
engineConfiguration.setBeans(new SpringBeanFactoryProxyMap(beanFactory));
return engineConfiguration;
}
@Bean
static public PropertyPlaceholderConfigurer archaiusPropertyPlaceholderConfigurer() throws IOException, ConfigurationException {
ConfigurationManager.loadPropertiesFromResources("chassis-test.properties");
ConfigurationManager.loadPropertiesFromResources("chassis-default.properties");
// force disable eureka
ConfigurationManager.getConfigInstance().setProperty("chassis.eureka.disable", true);
return new PropertyPlaceholderConfigurer() {
@Override
protected String resolvePlaceholder(String placeholder, Properties props, int systemPropertiesMode) {
return DynamicPropertyFactory.getInstance().getStringProperty(placeholder, "null").get();
}
};
}
@Bean
static public PropertyPlaceholderConfigurer archaiusPropertyPlaceholderConfigurer() throws IOException, ConfigurationException {
ConfigurationManager.loadPropertiesFromResources("chassis-test.properties");
ConfigurationManager.loadPropertiesFromResources("chassis-default.properties");
// force disable eureka
ConfigurationManager.getConfigInstance().setProperty("chassis.eureka.disable", true);
return new PropertyPlaceholderConfigurer() {
@Override
protected String resolvePlaceholder(String placeholder, Properties props, int systemPropertiesMode) {
return DynamicPropertyFactory.getInstance().getStringProperty(placeholder, "null").get();
}
};
}
protected PropertyConfigurer(StringEncryptor encryptor) {
this.propertyPlaceholderConfigurer = encryptor != null ? new EncryptablePropertyPlaceholderConfigurer(encryptor) : new PropertyPlaceholderConfigurer();
// Ensure that system properties override the spring-set properties.
propertyPlaceholderConfigurer.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
PropertiesPersister savingPropertiesPersister = new DefaultPropertiesPersister() {
@Override
public void load(Properties props, InputStream is) throws IOException {
props.put(HOSTNAME_KEY, HOSTNAME);
CougarNodeId.initialiseNodeId(props);
super.load(props, is);
for (String propName: props.stringPropertyNames()) {
allLoadedProperties.put(propName, System.getProperty(propName, props.getProperty(propName)));
}
}};
propertyPlaceholderConfigurer.setPropertiesPersister(savingPropertiesPersister);
}
@Test
public void testResourceInjectionWithResolvableDependencyType() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition abd = new RootBeanDefinition(ExtendedResourceInjectionBean.class);
abd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", abd);
RootBeanDefinition tbd = new RootBeanDefinition(TestBean.class);
tbd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("testBean4", tbd);
bf.registerResolvableDependency(BeanFactory.class, bf);
bf.registerResolvableDependency(INestedTestBean.class, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return new NestedTestBean();
}
});
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.setProperty("tb", "testBean4");
ppc.setProperties(props);
ppc.postProcessBeanFactory(bf);
ExtendedResourceInjectionBean bean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean");
INestedTestBean tb = bean.getTestBean6();
assertNotNull(tb);
ExtendedResourceInjectionBean anotherBean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertNotSame(anotherBean, bean);
assertNotSame(anotherBean.getTestBean6(), tb);
String[] depBeans = bf.getDependenciesForBean("annotatedBean");
assertEquals(1, depBeans.length);
assertEquals("testBean4", depBeans[0]);
}
@Bean
public static PropertyPlaceholderConfigurer properties() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[]{ new ClassPathResource("foo.properties") };
ppc.setLocations( resources );
ppc.setIgnoreUnresolvablePlaceholders( true );
return ppc;
}
@Test
@SuppressWarnings("resource")
public void formatFieldForAnnotationWithPlaceholders() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.setProperty("dateStyle", "S-");
props.setProperty("datePattern", "M-d-yy");
ppc.setProperties(props);
context.getBeanFactory().registerSingleton("ppc", ppc);
context.refresh();
context.getBeanFactory().initializeBean(formattingService, "formattingService");
formattingService.addFormatterForFieldAnnotation(new JodaDateTimeFormatAnnotationFormatterFactory());
doTestFormatFieldForAnnotation(ModelWithPlaceholders.class, false);
}
@Test
@SuppressWarnings("resource")
public void formatFieldForAnnotationWithPlaceholdersAndFactoryBean() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.setProperty("dateStyle", "S-");
props.setProperty("datePattern", "M-d-yy");
ppc.setProperties(props);
context.registerBeanDefinition("formattingService", new RootBeanDefinition(FormattingConversionServiceFactoryBean.class));
context.getBeanFactory().registerSingleton("ppc", ppc);
context.refresh();
formattingService = context.getBean("formattingService", FormattingConversionService.class);
doTestFormatFieldForAnnotation(ModelWithPlaceholders.class, false);
}
@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 propertyPlaceholderWithCron() {
String businessHoursCronExpression = "0 0 9-17 * * MON-FRI";
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertyPlaceholderConfigurer.class);
Properties properties = new Properties();
properties.setProperty("schedules.businessHours", businessHoursCronExpression);
placeholderDefinition.getPropertyValues().addPropertyValue("properties", properties);
BeanDefinition targetDefinition = new RootBeanDefinition(PropertyPlaceholderWithCronTestBean.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<CronTask> cronTasks = (List<CronTask>)
new DirectFieldAccessor(registrar).getPropertyValue("cronTasks");
assertEquals(1, cronTasks.size());
CronTask task = cronTasks.get(0);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
Object targetObject = runnable.getTarget();
Method targetMethod = runnable.getMethod();
assertEquals(target, targetObject);
assertEquals("x", targetMethod.getName());
assertEquals(businessHoursCronExpression, task.getExpression());
}
private void propertyPlaceholderWithFixedDelay(boolean durationFormat) {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertyPlaceholderConfigurer.class);
Properties properties = new Properties();
properties.setProperty("fixedDelay", (durationFormat ? "PT5S" : "5000"));
properties.setProperty("initialDelay", (durationFormat ? "PT1S" : "1000"));
placeholderDefinition.getPropertyValues().addPropertyValue("properties", properties);
BeanDefinition targetDefinition = new RootBeanDefinition(PropertyPlaceholderWithFixedDelayTestBean.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> fixedDelayTasks = (List<IntervalTask>)
new DirectFieldAccessor(registrar).getPropertyValue("fixedDelayTasks");
assertEquals(1, fixedDelayTasks.size());
IntervalTask task = fixedDelayTasks.get(0);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
Object targetObject = runnable.getTarget();
Method targetMethod = runnable.getMethod();
assertEquals(target, targetObject);
assertEquals("fixedDelay", targetMethod.getName());
assertEquals(1000L, task.getInitialDelay());
assertEquals(5000L, task.getInterval());
}
@Test
public void propertyPlaceholderForMetaAnnotation() {
String businessHoursCronExpression = "0 0 9-17 * * MON-FRI";
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertyPlaceholderConfigurer.class);
Properties properties = new Properties();
properties.setProperty("schedules.businessHours", businessHoursCronExpression);
placeholderDefinition.getPropertyValues().addPropertyValue("properties", properties);
BeanDefinition targetDefinition = new RootBeanDefinition(PropertyPlaceholderMetaAnnotationTestBean.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<CronTask> cronTasks = (List<CronTask>)
new DirectFieldAccessor(registrar).getPropertyValue("cronTasks");
assertEquals(1, cronTasks.size());
CronTask task = cronTasks.get(0);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
Object targetObject = runnable.getTarget();
Method targetMethod = runnable.getMethod();
assertEquals(target, targetObject);
assertEquals("y", targetMethod.getName());
assertEquals(businessHoursCronExpression, task.getExpression());
}
@Test
public void testResourceInjectionWithResolvableDependencyType() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor();
bpp.setBeanFactory(bf);
bf.addBeanPostProcessor(bpp);
RootBeanDefinition abd = new RootBeanDefinition(ExtendedResourceInjectionBean.class);
abd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", abd);
RootBeanDefinition tbd = new RootBeanDefinition(TestBean.class);
tbd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("testBean4", tbd);
bf.registerResolvableDependency(BeanFactory.class, bf);
bf.registerResolvableDependency(INestedTestBean.class, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return new NestedTestBean();
}
});
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.setProperty("tb", "testBean4");
ppc.setProperties(props);
ppc.postProcessBeanFactory(bf);
ExtendedResourceInjectionBean bean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean");
INestedTestBean tb = bean.getTestBean6();
assertNotNull(tb);
ExtendedResourceInjectionBean anotherBean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean");
assertNotSame(anotherBean, bean);
assertNotSame(anotherBean.getTestBean6(), tb);
String[] depBeans = bf.getDependenciesForBean("annotatedBean");
assertEquals(1, depBeans.length);
assertEquals("testBean4", depBeans[0]);
}
@Test
@SuppressWarnings("resource")
public void formatFieldForAnnotationWithPlaceholders() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.setProperty("dateStyle", "S-");
props.setProperty("datePattern", "M-d-yy");
ppc.setProperties(props);
context.getBeanFactory().registerSingleton("ppc", ppc);
context.refresh();
context.getBeanFactory().initializeBean(formattingService, "formattingService");
formattingService.addFormatterForFieldAnnotation(new JodaDateTimeFormatAnnotationFormatterFactory());
doTestFormatFieldForAnnotation(ModelWithPlaceholders.class, false);
}
@Test
@SuppressWarnings("resource")
public void formatFieldForAnnotationWithPlaceholdersAndFactoryBean() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
Properties props = new Properties();
props.setProperty("dateStyle", "S-");
props.setProperty("datePattern", "M-d-yy");
ppc.setProperties(props);
context.registerBeanDefinition("formattingService", new RootBeanDefinition(FormattingConversionServiceFactoryBean.class));
context.getBeanFactory().registerSingleton("ppc", ppc);
context.refresh();
formattingService = context.getBean("formattingService", FormattingConversionService.class);
doTestFormatFieldForAnnotation(ModelWithPlaceholders.class, false);
}
@Test
public void test() {
GenericApplicationContext ctx = new GenericApplicationContext();
ctx.registerBeanDefinition("ppc",
rootBeanDefinition(PropertyPlaceholderConfigurer.class)
.addPropertyValue("searchSystemEnvironment", false)
.getBeanDefinition());
ctx.refresh();
ctx.getBean("ppc");
}