@Test public void verifyEmbeddedConfigurationContext() { final PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer(); final Properties properties = new Properties(); properties.setProperty("mongodb.host", "ds061954.mongolab.com"); properties.setProperty("mongodb.port", "61954"); properties.setProperty("mongodb.userId", "casuser"); properties.setProperty("mongodb.userPassword", "Mellon"); properties.setProperty("cas.service.registry.mongo.db", "jasigcas"); configurer.setProperties(properties); final FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext( new String[]{"src/main/resources/META-INF/spring/mongo-services-context.xml"}, false); ctx.getBeanFactoryPostProcessors().add(configurer); ctx.refresh(); final MongoServiceRegistryDao dao = new MongoServiceRegistryDao(); dao.setMongoTemplate(ctx.getBean("mongoTemplate", MongoTemplate.class)); cleanAll(dao); assertTrue(dao.load().isEmpty()); saveAndLoad(dao); }
@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()); }
@Test public void testScanWithExplicitSqlSessionFactoryViaPlaceholder() throws Exception { setupSqlSessionFactory("sqlSessionFactory2"); // use a property placeholder for the session factory name applicationContext.getBeanDefinition("mapperScanner").getPropertyValues().add( "sqlSessionFactoryBeanName", "${sqlSessionFactoryBeanNameProperty}"); Properties props = new java.util.Properties(); props.put("sqlSessionFactoryBeanNameProperty", "sqlSessionFactory2"); GenericBeanDefinition propertyDefinition = new GenericBeanDefinition(); propertyDefinition.setBeanClass(PropertyPlaceholderConfigurer.class); propertyDefinition.getPropertyValues().add("properties", props); applicationContext.registerBeanDefinition("propertiesPlaceholder", propertyDefinition); testInterfaceScan(); }
/** * Gets the property placeholder configurer. * * @return the property placeholder configurer */ @Bean(name = "propertyPlaceholderConfigurer") public static PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer() { logger.debug("Instantiated propertyPlaceholderConfigurer"); PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer(); configurer.setLocation(new ClassPathResource("stats.properties")); configurer.setNullValue("NULL"); Properties properties = new Properties(); properties.put("psiprobe.tools.mail.to", "NULL"); properties.put("psiprobe.tools.mail.subjectPrefix", "[PSI Probe]"); configurer.setProperties(properties); configurer.setSystemPropertiesModeName("SYSTEM_PROPERTIES_MODE_OVERRIDE"); return configurer; }
@Bean public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() { final PropertyPlaceholderConfigurer propConfig = new PropertyPlaceholderConfigurer(); propConfig.setIgnoreResourceNotFound(true); String sysPropPath = System.getProperty("app.cfg"); if (sysPropPath != null) { propConfig.setLocation(new FileSystemResource(sysPropPath)); } else { propConfig.setLocation(new ClassPathResource(APP_PROPERTIES)); } return propConfig; }
/** * Property placeholder configurer. * * @return the property placeholder configurer */ @Bean public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() { PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); final List<Resource> resourceLst = new ArrayList<>(); resourceLst.add(new ClassPathResource("/hibernateTest.properties")); resourceLst.add(new ClassPathResource("/config.properties")); resourceLst.add(new ClassPathResource("/bankRemittance.properties")); resourceLst.add(new ClassPathResource("/firebaseMessaging.properties")); resourceLst.add(new ClassPathResource("/firebaseWeb.properties")); resourceLst.add(new ClassPathResource("/paypal.properties")); resourceLst.add(new ClassPathResource("/recaptcha.properties")); //initializeFirebase("configFirebase", "/members-firebase-adminsdk.json"); ppc.setLocations(resourceLst.toArray(new Resource[] {})); return ppc; }
@Test public void testPropertyPlaceholderConfigurerWithSystemPropertyInLocation() { StaticApplicationContext ac = new StaticApplicationContext(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("spouse", new RuntimeBeanReference("${ref}")); ac.registerSingleton("tb", TestBean.class, pvs); pvs = new MutablePropertyValues(); pvs.add("location", "${user.dir}/test"); ac.registerSingleton("configurer", PropertyPlaceholderConfigurer.class, pvs); try { ac.refresh(); fail("Should have thrown BeanInitializationException"); } catch (BeanInitializationException ex) { // expected assertTrue(ex.getCause() instanceof FileNotFoundException); // slight hack for Linux/Unix systems String userDir = StringUtils.cleanPath(System.getProperty("user.dir")); if (userDir.startsWith("/")) { userDir = userDir.substring(1); } assertTrue(ex.getMessage().indexOf(userDir) != -1); } }
@Test public void testPropertyPlaceholderConfigurerWithUnresolvableSystemPropertiesInLocation() { StaticApplicationContext ac = new StaticApplicationContext(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("spouse", new RuntimeBeanReference("${ref}")); ac.registerSingleton("tb", TestBean.class, pvs); pvs = new MutablePropertyValues(); pvs.add("location", "${myprop}/test/${myprop}"); ac.registerSingleton("configurer", PropertyPlaceholderConfigurer.class, pvs); try { ac.refresh(); fail("Should have thrown BeanInitializationException"); } catch (BeanInitializationException ex) { // expected assertTrue(ex.getMessage().contains("myprop")); } }
@Test public void testPropertyPlaceholderConfigurerWithMultiLevelCircularReference() { StaticApplicationContext ac = new StaticApplicationContext(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("name", "name${var}"); ac.registerSingleton("tb1", TestBean.class, pvs); pvs = new MutablePropertyValues(); pvs.add("properties", "var=${m}var\nm=${var2}\nvar2=${var}"); ac.registerSingleton("configurer1", PropertyPlaceholderConfigurer.class, pvs); try { ac.refresh(); fail("Should have thrown BeanDefinitionStoreException"); } catch (BeanDefinitionStoreException ex) { // expected } }
@Test public void testPropertyPlaceholderConfigurerWithNestedCircularReference() { StaticApplicationContext ac = new StaticApplicationContext(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("name", "name${var}"); ac.registerSingleton("tb1", TestBean.class, pvs); pvs = new MutablePropertyValues(); pvs.add("properties", "var=${m}var\nm=${var2}\nvar2=${m}"); ac.registerSingleton("configurer1", PropertyPlaceholderConfigurer.class, pvs); try { ac.refresh(); fail("Should have thrown BeanDefinitionStoreException"); } catch (BeanDefinitionStoreException ex) { // expected } }
@Test public void testPropertyPlaceholderConfigurerWithNestedUnresolvableReference() { StaticApplicationContext ac = new StaticApplicationContext(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("name", "name${var}"); ac.registerSingleton("tb1", TestBean.class, pvs); pvs = new MutablePropertyValues(); pvs.add("properties", "var=${m}var\nm=${var2}\nvar2=${m2}"); ac.registerSingleton("configurer1", PropertyPlaceholderConfigurer.class, pvs); try { ac.refresh(); fail("Should have thrown BeanDefinitionStoreException"); } catch (BeanDefinitionStoreException ex) { // expected ex.printStackTrace(); } }
@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()); String s = (String) applicationContext.getBean("string"); assertEquals("No properties replaced", "spam", s); } finally { if (value!=null) { System.setProperty("foo", value); } } }
@Test 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"); try { MetaValueBean valueBean = ac.getBean(MetaValueBean.class); assertEquals(new LocalDate(2009, 10, 31), new LocalDate(valueBean.date)); } finally { System.clearProperty("myDate"); } }
@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(); } }; }
/** * Creates an instance of a {@code TidaServer}, which is completely * auto-wired according to the configuration. * * @param properties * properties to be set for the configuration * * @return the created {@code TidaServer} instance */ public static TidaServer create(final Properties properties) { final List<PropertiesLoaderSupport> holders; if (properties == null) { holders = null; } else { holders = new ArrayList<PropertiesLoaderSupport>(); // create a propertyHolder for the properties final SpringPropertyHolder holder = new SpringPropertyHolder(); holder.setProperties(properties); holder.setLocalOverride(true); holder.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_NEVER); holder.setOtherHolderOverride(false); // add the propertyHolder holders.add(holder); } // create the instance final ConfigurationCoreSettings settings = ConfigurationCoreSettings .loadCoreSettings("sbconfigurator-core.xml", TidaConfig.class, holders, null); return settings.getConfiguration().getModule("tidaServer"); }
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); }
public IdentifiersNAServiceImpl() throws RemoteException { super(); try { String naConfigurationFile = getConfiguration().getNaConfigurationFile(); String naProperties = getConfiguration().getNaPropertiesFile(); FileSystemResource naConfResource = new FileSystemResource(naConfigurationFile); FileSystemResource naPropertiesResource = new FileSystemResource(naProperties); XmlBeanFactory factory = new XmlBeanFactory(naConfResource); PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); cfg.setLocation(naPropertiesResource); cfg.postProcessBeanFactory(factory); this.namingAuthority = (MaintainerNamingAuthority) factory.getBean(NA_BEAN_NAME, MaintainerNamingAuthority.class); } catch (Exception e) { String message = "Problem inititializing NamingAuthority while loading configuration:" + e.getMessage(); LOG.error(message, e); throw new RemoteException(message, e); } }
public GlobalModelExchangeImpl() throws RemoteException { super(); try { String gmeConfigurationFile = getConfiguration().getGmeConfigurationFile(); String gmeProperties = getConfiguration().getGmePropertiesFile(); FileSystemResource gmeConfResource = new FileSystemResource(gmeConfigurationFile); FileSystemResource gmePropertiesResource = new FileSystemResource(gmeProperties); XmlBeanFactory factory = new XmlBeanFactory(gmeConfResource); PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); cfg.setLocation(gmePropertiesResource); cfg.postProcessBeanFactory(factory); this.gme = (GME) factory.getBean(GME_BEAN_NAME, GME.class); } catch (Exception e) { String message = "Problem inititializing GME while loading configuration:" + e.getMessage(); LOG.error(message, e); throw new RemoteException(message, e); } }
public CredentialDelegationServiceImpl() throws RemoteException { super(); try { this.log = LogFactory.getLog(this.getClass().getName()); String conf = this.getConfiguration().getCdsConfiguration(); String properties = this.getConfiguration().getCdsProperties(); FileSystemResource fsr = new FileSystemResource(conf); XmlBeanFactory factory = new XmlBeanFactory(fsr); PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); cfg.setLocation(new FileSystemResource(properties)); cfg.postProcessBeanFactory(factory); Database db = (Database) factory .getBean(ConfigurationConstants.DATABASE_CONFIGURATION_BEAN); db.createDatabaseIfNeeded(); cds = (DelegationManager) factory .getBean(ConfigurationConstants.CDS_BEAN); home = (DelegatedCredentialResourceHome) getDelegatedCredentialResourceHome(); home.setCDS(cds); } catch (Exception e) { log.error(e.getMessage(), e); throw Errors.getInternalFault( "Error initializing the Credential Delegation Service.", e); } }
@Bean public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() { String password = System.getenv(BOD_ENCRYPTION_PASSWORD_ENV_VAR); if (StringUtils.isEmpty(password)) { LOGGER.warn(BOD_ENCRYPTION_PASSWORD_ENV_VAR + " not set, encrypted properties will not load correctly."); password = BOD_ENCRYPTION_PASSWORD_ENV_VAR + " not set"; } StrongTextEncryptor encryptor = new StrongTextEncryptor(); encryptor.setPassword(password); EncryptablePropertyPlaceholderConfigurer configurer = new EncryptablePropertyPlaceholderConfigurer(encryptor); configurer.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE); Resource[] resources = BodProperties.getPropertyResources(); LOGGER.info("Using property files: {}", Stream.of(resources).map(Resource::toString).collect(joining(","))); configurer.setLocations(resources); return configurer; }
@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 (element.getAttribute(SYSTEM_PROPERTIES_MODE_ATTRIB).equals(SYSTEM_PROPERTIES_MODE_DEFAULT)) { return PropertySourcesPlaceholderConfigurer.class; } // the user has explicitly specified a value for system-properties-mode. Revert // to PropertyPlaceholderConfigurer to ensure backward compatibility. return PropertyPlaceholderConfigurer.class; }
/** * Load the properties files used in application contexts here * * @return the initialized instance of the PropertyPlaceholderConfigurer class */ @Bean(name="properties") @Scope(BeanDefinition.SCOPE_SINGLETON) public PropertyPlaceholderConfigurer conversionService() { PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer(); Resource resource1 = new ClassPathResource("application_file_1.properties"); Resource resource2 = new ClassPathResource("application_file_2.properties"); configurer.setLocations(resource1, resource2); return configurer; }
@Override public void initialize(AbstractApplicationContext applicationContext) { PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer(); //load test.properties propertyPlaceholderConfigurer.setLocation(new ClassPathResource("test.properties")); applicationContext.addBeanFactoryPostProcessor(propertyPlaceholderConfigurer); }
@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("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()); }
@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()); }