org.springframework.beans.factory.config.PropertyPlaceholderConfigurer Java Examples

The following examples show how to use org.springframework.beans.factory.config.PropertyPlaceholderConfigurer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServletAnnotationControllerHandlerMethodTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #2
Source File: ConfigurationClassProcessingTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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();
}
 
Example #3
Source File: ChassisHystrixTestConfiguration.java    From chassis with Apache License 2.0 6 votes vote down vote up
@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();
        }
    };
}
 
Example #4
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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());
}
 
Example #5
Source File: ChassisConfigTestConfiguration.java    From chassis with Apache License 2.0 6 votes vote down vote up
@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();
        }
    };
}
 
Example #6
Source File: FormattingConversionServiceTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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");
	}
}
 
Example #7
Source File: PropertyConfigurer.java    From cougar with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #8
Source File: BeansConfigurationHelper.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #9
Source File: BeanFactoryPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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);
}
 
Example #10
Source File: FormattingConversionServiceTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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");
	}
}
 
Example #11
Source File: ServletAnnotationControllerHandlerMethodTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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());
}
 
Example #12
Source File: FormattingConversionServiceTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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");
	}
}
 
Example #13
Source File: ContextNamespaceHandlerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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);
		}
	}
}
 
Example #14
Source File: BeanFactoryPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #15
Source File: ConfigurationClassProcessingTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #16
Source File: PropertyPlaceholderConfigurerTool.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #17
Source File: ChildApplicationContextFactory.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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();
}
 
Example #18
Source File: ChildApplicationContextFactory.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #19
Source File: CoreAppConfig.java    From logsniffer with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns a general properties placeholder configurer based on
 * {@link #logSnifferProperties()}.
 * 
 * @param props
 *            autowired logSnifferProperties bean
 * @return A general properties placeholder configurer.
 * @throws IOException
 */
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
@Autowired
public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer(
		@Qualifier(BEAN_LOGSNIFFER_PROPS) final Properties props) throws IOException {
	final PropertyPlaceholderConfigurer c = new PropertyPlaceholderConfigurer();
	c.setIgnoreResourceNotFound(true);
	c.setIgnoreUnresolvablePlaceholders(true);
	c.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
	c.setProperties(props);
	return c;
}
 
Example #20
Source File: SpringUtils.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static PropertyPlaceholderConfigurer newApplicationConf(boolean searchSystemEnvironment, String... locations){
	Assert.notEmpty(locations);
	PropertyPlaceholderConfigurer ppc = new JFishPropertyPlaceholder();
	ppc.setIgnoreResourceNotFound(true);
	ppc.setIgnoreUnresolvablePlaceholders(true);
	ppc.setSearchSystemEnvironment(searchSystemEnvironment);
	List<Resource> resources = new ArrayList<Resource>();
	for(String path : locations){
		resources.add(new ClassPathResource(path));
	}
	ppc.setLocations(resources.toArray(new Resource[resources.size()]));
	return ppc;
}
 
Example #21
Source File: ChassisEurekaTestConfiguration.java    From chassis with Apache License 2.0 5 votes vote down vote up
@Bean
static public PropertyPlaceholderConfigurer archaiusPropertyPlaceholderConfigurer() throws IOException, ConfigurationException {
	
    ConfigurationManager.loadPropertiesFromResources("chassis-test.properties");
    ConfigurationManager.loadPropertiesFromResources("chassis-default.properties");
    
    return new PropertyPlaceholderConfigurer() {
        @Override
        protected String resolvePlaceholder(String placeholder, Properties props, int systemPropertiesMode) {
            return DynamicPropertyFactory.getInstance().getStringProperty(placeholder, "null").get();
        }
    };
}
 
Example #22
Source File: CommonAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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]);
}
 
Example #23
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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();

	Object postProcessor = context.getBean("postProcessor");
	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());
}
 
Example #24
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void propertyPlaceholderWithFixedRate() {
	BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
	BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertyPlaceholderConfigurer.class);
	Properties properties = new Properties();
	properties.setProperty("fixedRate", "3000");
	properties.setProperty("initialDelay", "1000");
	placeholderDefinition.getPropertyValues().addPropertyValue("properties", properties);
	BeanDefinition targetDefinition = new RootBeanDefinition(PropertyPlaceholderWithFixedRateTestBean.class);
	context.registerBeanDefinition("placeholder", placeholderDefinition);
	context.registerBeanDefinition("postProcessor", processorDefinition);
	context.registerBeanDefinition("target", targetDefinition);
	context.refresh();

	Object postProcessor = context.getBean("postProcessor");
	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());
}
 
Example #25
Source File: JsHttpRequestTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void additionalSpringConfiguration(GenericApplicationContext applicationContext) throws Exception {
    // bring in some property values from a Properties file
    PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
    Properties properties = new Properties();
    properties.setProperty("staticResourceURL", getStaticResourceURL());
    cfg.setProperties(properties);
    // now actually do the replacement
    cfg.postProcessBeanFactory(applicationContext.getBeanFactory());

}
 
Example #26
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void propertyPlaceholderWithFixedDelay() {
	BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
	BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertyPlaceholderConfigurer.class);
	Properties properties = new Properties();
	properties.setProperty("fixedDelay", "5000");
	properties.setProperty("initialDelay", "1000");
	placeholderDefinition.getPropertyValues().addPropertyValue("properties", properties);
	BeanDefinition targetDefinition = new RootBeanDefinition(PropertyPlaceholderWithFixedDelayTestBean.class);
	context.registerBeanDefinition("placeholder", placeholderDefinition);
	context.registerBeanDefinition("postProcessor", processorDefinition);
	context.registerBeanDefinition("target", targetDefinition);
	context.refresh();

	Object postProcessor = context.getBean("postProcessor");
	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());
}
 
Example #27
Source File: CommonAnnotationBeanPostProcessorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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]);
}
 
Example #28
Source File: ScheduledAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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("placeholder", placeholderDefinition);
	context.registerBeanDefinition("postProcessor", processorDefinition);
	context.registerBeanDefinition("target", targetDefinition);
	context.refresh();

	Object postProcessor = context.getBean("postProcessor");
	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());
}
 
Example #29
Source File: PropertyPlaceholderBeanDefinitionParser.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #30
Source File: ContextNamespaceHandlerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void propertyPlaceholderLocation() throws Exception {
	ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
			"contextNamespaceHandlerTests-location.xml", getClass());
	Map<String, PropertyPlaceholderConfigurer> beans = applicationContext
			.getBeansOfType(PropertyPlaceholderConfigurer.class);
	assertFalse("No PropertyPlaceholderConfigurer found", beans.isEmpty());
	assertEquals("bar", applicationContext.getBean("foo"));
	assertEquals("foo", applicationContext.getBean("bar"));
	assertEquals("maps", applicationContext.getBean("spam"));
}