/** * This implementation applies the passed-in job data map as bean property * values, and delegates to {@code executeInternal} afterwards. * @see #executeInternal */ @Override public final void execute(JobExecutionContext context) throws JobExecutionException { try { // Reflectively adapting to differences between Quartz 1.x and Quartz 2.0... Scheduler scheduler = (Scheduler) ReflectionUtils.invokeMethod(getSchedulerMethod, context); Map<?, ?> mergedJobDataMap = (Map<?, ?>) ReflectionUtils.invokeMethod(getMergedJobDataMapMethod, context); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValues(scheduler.getContext()); pvs.addPropertyValues(mergedJobDataMap); bw.setPropertyValues(pvs, true); } catch (SchedulerException ex) { throw new JobExecutionException(ex); } executeInternal(context); }
/** * Create the job instance, populating it with property values taken * from the scheduler context, job data map and trigger data map. */ @Override protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { Object job = super.createJobInstance(bundle); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job); if (isEligibleForPropertyPopulation(bw.getWrappedInstance())) { MutablePropertyValues pvs = new MutablePropertyValues(); if (this.schedulerContext != null) { pvs.addPropertyValues(this.schedulerContext); } pvs.addPropertyValues(getJobDetailDataMap(bundle)); pvs.addPropertyValues(getTriggerDataMap(bundle)); if (this.ignoredUnknownProperties != null) { for (String propName : this.ignoredUnknownProperties) { if (pvs.contains(propName) && !bw.isWritableProperty(propName)) { pvs.removePropertyValue(propName); } } bw.setPropertyValues(pvs); } else { bw.setPropertyValues(pvs, true); } } return job; }
/** * Check the given property values for field defaults, * i.e. for fields that start with the field default prefix. * <p>The existence of a field defaults indicates that the specified * value should be used if the field is otherwise not present. * @param mpvs the property values to be bound (can be modified) * @see #getFieldDefaultPrefix */ protected void checkFieldDefaults(MutablePropertyValues mpvs) { if (getFieldDefaultPrefix() != null) { String fieldDefaultPrefix = getFieldDefaultPrefix(); PropertyValue[] pvArray = mpvs.getPropertyValues(); for (PropertyValue pv : pvArray) { if (pv.getName().startsWith(fieldDefaultPrefix)) { String field = pv.getName().substring(fieldDefaultPrefix.length()); if (getPropertyAccessor().isWritableProperty(field) && !mpvs.contains(field)) { mpvs.add(field, pv.getValue()); } mpvs.removePropertyValue(pv); } } } }
/** * Check the given property values for field markers, * i.e. for fields that start with the field marker prefix. * <p>The existence of a field marker indicates that the specified * field existed in the form. If the property values do not contain * a corresponding field value, the field will be considered as empty * and will be reset appropriately. * @param mpvs the property values to be bound (can be modified) * @see #getFieldMarkerPrefix * @see #getEmptyValue(String, Class) */ protected void checkFieldMarkers(MutablePropertyValues mpvs) { if (getFieldMarkerPrefix() != null) { String fieldMarkerPrefix = getFieldMarkerPrefix(); PropertyValue[] pvArray = mpvs.getPropertyValues(); for (PropertyValue pv : pvArray) { if (pv.getName().startsWith(fieldMarkerPrefix)) { String field = pv.getName().substring(fieldMarkerPrefix.length()); if (getPropertyAccessor().isWritableProperty(field) && !mpvs.contains(field)) { Class<?> fieldType = getPropertyAccessor().getPropertyType(field); mpvs.add(field, getEmptyValue(field, fieldType)); } mpvs.removePropertyValue(pv); } } } }
/** * Bind all multipart files contained in the given request, if any * (in case of a multipart request). * <p>Multipart files will only be added to the property values if they * are not empty or if we're configured to bind empty multipart files too. * @param multipartFiles Map of field name String to MultipartFile object * @param mpvs the property values to be bound (can be modified) * @see org.springframework.web.multipart.MultipartFile * @see #setBindEmptyMultipartFiles */ protected void bindMultipart(Map<String, List<MultipartFile>> multipartFiles, MutablePropertyValues mpvs) { for (Map.Entry<String, List<MultipartFile>> entry : multipartFiles.entrySet()) { String key = entry.getKey(); List<MultipartFile> values = entry.getValue(); if (values.size() == 1) { MultipartFile value = values.get(0); if (isBindEmptyMultipartFiles() || !value.isEmpty()) { mpvs.add(key, value); } } else { mpvs.add(key, values); } } }
/** * Fill in any missing property values with references to * other beans in this factory if autowire is set to "byName". * @param beanName the name of the bean we're wiring up. * Useful for debugging messages; not used functionally. * @param mbd bean definition to update through autowiring * @param bw BeanWrapper from which we can obtain information about the bean * @param pvs the PropertyValues to register wired objects with */ protected void autowireByName( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); for (String propertyName : propertyNames) { if (containsBean(propertyName)) { Object bean = getBean(propertyName); pvs.add(propertyName, bean); registerDependentBean(propertyName, beanName); if (logger.isDebugEnabled()) { logger.debug("Added autowiring by name from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + propertyName + "'"); } } else { if (logger.isTraceEnabled()) { logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName + "' by name: no matching bean found"); } } } }
@Override public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) { if (node instanceof Attr) { Attr attr = (Attr) node; String propertyName = parserContext.getDelegate().getLocalName(attr); String propertyValue = attr.getValue(); MutablePropertyValues pvs = definition.getBeanDefinition().getPropertyValues(); if (pvs.contains(propertyName)) { parserContext.getReaderContext().error("Property '" + propertyName + "' is already defined using " + "both <property> and inline syntax. Only one approach may be used per property.", attr); } if (propertyName.endsWith(REF_SUFFIX)) { propertyName = propertyName.substring(0, propertyName.length() - REF_SUFFIX.length()); pvs.add(Conventions.attributeNameToPropertyName(propertyName), new RuntimeBeanReference(propertyValue)); } else { pvs.add(Conventions.attributeNameToPropertyName(propertyName), propertyValue); } } return definition; }
private void unwrapDefinitions(BeanDefinition advisorDefinition, BeanDefinition pointcutDefinition) { MutablePropertyValues pvs = advisorDefinition.getPropertyValues(); BeanReference adviceReference = (BeanReference) pvs.getPropertyValue("adviceBeanName").getValue(); if (pointcutDefinition != null) { this.beanReferences = new BeanReference[] {adviceReference}; this.beanDefinitions = new BeanDefinition[] {advisorDefinition, pointcutDefinition}; this.description = buildDescription(adviceReference, pointcutDefinition); } else { BeanReference pointcutReference = (BeanReference) pvs.getPropertyValue("pointcut").getValue(); this.beanReferences = new BeanReference[] {adviceReference, pointcutReference}; this.beanDefinitions = new BeanDefinition[] {advisorDefinition}; this.description = buildDescription(adviceReference, pointcutReference); } }
@Override public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { AnnotationAttributes enableMenu = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(EnableMenu.class .getName(), false)); if (enableMenu != null) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(DefaultMenuPlugin.class); AbstractBeanDefinition beanDefinition = builder.getBeanDefinition(); MutablePropertyValues mutablePropertyValues = new MutablePropertyValues(); mutablePropertyValues.add("extensionPointId", enableMenu.getString("extensionPointId")); mutablePropertyValues.add("pluginId", enableMenu.getString("pluginId")); mutablePropertyValues.add("menu", toMenu(enableMenu.getAnnotationArray("menu"))); beanDefinition.setPropertyValues(mutablePropertyValues); registry.registerBeanDefinition("menuPlugin:" + enableMenu.getString("pluginId"), beanDefinition); } }
/** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void postProcessBeanFactory( ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException { String[] igniteConfigNames = configurableListableBeanFactory.getBeanNamesForType(IgniteConfiguration.class); if (igniteConfigNames.length != 1) { throw new IllegalArgumentException("Spring config must contain exactly one ignite configuration!"); } String[] activeStoreConfigNames = configurableListableBeanFactory.getBeanNamesForType(BaseActiveStoreConfiguration.class); if (activeStoreConfigNames.length != 1) { throw new IllegalArgumentException("Spring config must contain exactly one active store configuration!"); } BeanDefinition igniteConfigDef = configurableListableBeanFactory.getBeanDefinition(igniteConfigNames[0]); MutablePropertyValues propertyValues = igniteConfigDef.getPropertyValues(); if (!propertyValues.contains(USER_ATTRS_PROP_NAME)) { propertyValues.add(USER_ATTRS_PROP_NAME, new ManagedMap()); } PropertyValue propertyValue = propertyValues.getPropertyValue(USER_ATTRS_PROP_NAME); Map userAttrs = (Map)propertyValue.getValue(); TypedStringValue key = new TypedStringValue(CONFIG_USER_ATTR); RuntimeBeanReference value = new RuntimeBeanReference(beanName); userAttrs.put(key, value); }
protected void initJob(TriggerFiredBundle bundle, Object job) { // The following code is copied from SpringBeanJobFactory in spring-context-support-4.2.5.RELEASE BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job); if (isEligibleForPropertyPopulation(bw.getWrappedInstance())) { MutablePropertyValues pvs = new MutablePropertyValues(); if (schedulerContext != null) { pvs.addPropertyValues(this.schedulerContext); } pvs.addPropertyValues(bundle.getJobDetail().getJobDataMap()); pvs.addPropertyValues(bundle.getTrigger().getJobDataMap()); if (this.ignoredUnknownProperties != null) { for (String propName : this.ignoredUnknownProperties) { if (pvs.contains(propName) && !bw.isWritableProperty(propName)) { pvs.removePropertyValue(propName); } } bw.setPropertyValues(pvs); } else { bw.setPropertyValues(pvs, true); } } }
/** * Fill in any missing property values with references to * other beans in this factory if autowire is set to "byName". * @param beanName the name of the bean we're wiring up. * Useful for debugging messages; not used functionally. * @param mbd bean definition to update through autowiring * @param bw BeanWrapper from which we can obtain information about the bean * @param pvs the PropertyValues to register wired objects with */ protected void autowireByName( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { //��ȡ��ǰbean�������� String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); for (String propertyName : propertyNames) { if (containsBean(propertyName)) { Object bean = getBean(propertyName); pvs.add(propertyName, bean); registerDependentBean(propertyName, beanName); if (logger.isDebugEnabled()) { logger.debug("Added autowiring by name from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + propertyName + "'"); } } else { if (logger.isTraceEnabled()) { logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName + "' by name: no matching bean found"); } } } }
@Test public void testServletContextParameterFactoryBeanWithAttributeNotFound() { MockServletContext sc = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("initParamName", "myParam"); wac.registerSingleton("importedParam", ServletContextParameterFactoryBean.class, pvs); try { wac.refresh(); fail("Should have thrown BeanCreationException"); } catch (BeanCreationException ex) { // expected assertTrue(ex.getCause() instanceof IllegalStateException); assertTrue(ex.getCause().getMessage().contains("myParam")); } }
private MutablePropertyValues getPropertyValuesForNamePrefix( MutablePropertyValues propertyValues) { if (!StringUtils.hasText(this.namePrefix) && !this.ignoreNestedProperties) { return propertyValues; } MutablePropertyValues rtn = new MutablePropertyValues(); for (PropertyValue value : propertyValues.getPropertyValues()) { String name = value.getName(); for (String prefix : new RelaxedNames(stripLastDot(this.namePrefix))) { for (String separator : new String[] { ".", "_" }) { String candidate = (StringUtils.hasLength(prefix) ? prefix + separator : prefix); if (name.startsWith(candidate)) { name = name.substring(candidate.length()); if (!(this.ignoreNestedProperties && name.contains("."))) { PropertyOrigin propertyOrigin = OriginCapablePropertyValue .getOrigin(value); rtn.addPropertyValue(new OriginCapablePropertyValue(name, value.getValue(), propertyOrigin)); } } } } } return rtn; }
@Test public void testBindingErrorWithFormatter() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb); FormattingConversionService conversionService = new FormattingConversionService(); DefaultConversionService.addDefaultConverters(conversionService); conversionService.addFormatterForFieldType(Float.class, new NumberStyleFormatter()); binder.setConversionService(conversionService); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("myFloat", "1x2"); LocaleContextHolder.setLocale(Locale.GERMAN); try { binder.bind(pvs); assertEquals(new Float(0.0), tb.getMyFloat()); assertEquals("1x2", binder.getBindingResult().getFieldValue("myFloat")); assertTrue(binder.getBindingResult().hasFieldErrors("myFloat")); } finally { LocaleContextHolder.resetLocaleContext(); } }
@Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { Map<Object, Object> targetDataSources = new HashMap<Object, Object>(); // 将主数据源添加到更多数据源中 targetDataSources.put("dataSource", defaultDataSource); DynamicDataSourceContextHolder.dataSourceIds.add("dataSource"); // 添加更多数据源 targetDataSources.putAll(customDataSources); for (String key : customDataSources.keySet()) { DynamicDataSourceContextHolder.dataSourceIds.add(key); } // 创建DynamicDataSource GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(DynamicDataSource.class); beanDefinition.setSynthetic(true); MutablePropertyValues mpv = beanDefinition.getPropertyValues(); mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource); mpv.addPropertyValue("targetDataSources", targetDataSources); registry.registerBeanDefinition("dataSource", beanDefinition); logger.info("Dynamic DataSource Registry"); }
@Test public void testBindingWithOverlappingAllowedAndDisallowedFields() throws Exception { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod); binder.setAllowedFields("name", "age"); binder.setDisallowedFields("age"); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("name", "Rod"); pvs.add("age", "32x"); binder.bind(pvs); binder.close(); assertTrue("changed name correctly", rod.getName().equals("Rod")); assertTrue("did not change age", rod.getAge() == 0); String[] disallowedFields = binder.getBindingResult().getSuppressedFields(); assertEquals(1, disallowedFields.length); assertEquals("age", disallowedFields[0]); }
@Test public void postProcessEmbeddedServletContainerFactory() throws Exception { RootBeanDefinition bd = new RootBeanDefinition( MockEmbeddedServletContainerFactory.class); MutablePropertyValues pv = new MutablePropertyValues(); pv.add("port", "${port}"); bd.setPropertyValues(pv); this.context.registerBeanDefinition("embeddedServletContainerFactory", bd); PropertySourcesPlaceholderConfigurer propertySupport = new PropertySourcesPlaceholderConfigurer(); Properties properties = new Properties(); properties.put("port", 8080); propertySupport.setProperties(properties); this.context.registerBeanDefinition("propertySupport", beanDefinition(propertySupport)); this.context.refresh(); assertThat(getEmbeddedServletContainerFactory().getContainer().getPort()) .isEqualTo(8080); }
@Test public void testEditorForNestedIndexedField() { IndexedTestBean tb = new IndexedTestBean(); tb.getArray()[0].setNestedIndexedBean(new IndexedTestBean()); tb.getArray()[1].setNestedIndexedBean(new IndexedTestBean()); DataBinder binder = new DataBinder(tb, "tb"); binder.registerCustomEditor(String.class, "array.nestedIndexedBean.list.name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("list" + text); } @Override public String getAsText() { return ((String) getValue()).substring(4); } }); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("array[0].nestedIndexedBean.list[0].name", "test1"); pvs.add("array[1].nestedIndexedBean.list[1].name", "test2"); binder.bind(pvs); assertEquals("listtest1", ((TestBean)tb.getArray()[0].getNestedIndexedBean().getList().get(0)).getName()); assertEquals("listtest2", ((TestBean)tb.getArray()[1].getNestedIndexedBean().getList().get(1)).getName()); assertEquals("test1", binder.getBindingResult().getFieldValue("array[0].nestedIndexedBean.list[0].name")); assertEquals("test2", binder.getBindingResult().getFieldValue("array[1].nestedIndexedBean.list[1].name")); }
@Test public void testProcessInjectionBasedOnServletContext() { StaticWebApplicationContext wac = new StaticWebApplicationContext(); AnnotationConfigUtils.registerAnnotationConfigProcessors(wac); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("name", "tb"); wac.registerSingleton("testBean", TestBean.class, pvs); MockServletContext sc = new MockServletContext(); wac.setServletContext(sc); wac.refresh(); sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); InjectionTarget target = new InjectionTarget(); SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(target, sc); assertTrue(target.testBean instanceof TestBean); assertEquals("tb", target.name); }
@Test public void testConfigureBeanWithAutowiring() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); lbf.registerBeanDefinition("spouse", bd); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("age", "99"); RootBeanDefinition tbd = new RootBeanDefinition(TestBean.class); tbd.setAutowireMode(RootBeanDefinition.AUTOWIRE_BY_NAME); lbf.registerBeanDefinition("test", tbd); TestBean tb = new TestBean(); lbf.configureBean(tb, "test"); assertSame(lbf, tb.getBeanFactory()); TestBean spouse = (TestBean) lbf.getBean("spouse"); assertEquals(spouse, tb.getSpouse()); }
@Test public void bindingNoErrors() throws Exception { FieldAccessBean rod = new FieldAccessBean(); DataBinder binder = new DataBinder(rod, "person"); assertTrue(binder.isIgnoreUnknownFields()); binder.initDirectFieldAccess(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue(new PropertyValue("name", "Rod")); pvs.addPropertyValue(new PropertyValue("age", new Integer(32))); pvs.addPropertyValue(new PropertyValue("nonExisting", "someValue")); binder.bind(pvs); binder.close(); assertTrue("changed name correctly", rod.getName().equals("Rod")); assertTrue("changed age correctly", rod.getAge() == 32); Map<?, ?> m = binder.getBindingResult().getModel(); assertTrue("There is one element in map", m.size() == 2); FieldAccessBean tb = (FieldAccessBean) m.get("person"); assertTrue("Same object", tb.equals(rod)); }
@Test public void bindingNoErrorsNotIgnoreUnknown() throws Exception { FieldAccessBean rod = new FieldAccessBean(); DataBinder binder = new DataBinder(rod, "person"); binder.initDirectFieldAccess(); binder.setIgnoreUnknownFields(false); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue(new PropertyValue("name", "Rod")); pvs.addPropertyValue(new PropertyValue("age", new Integer(32))); pvs.addPropertyValue(new PropertyValue("nonExisting", "someValue")); try { binder.bind(pvs); fail("Should have thrown NotWritablePropertyException"); } catch (NotWritablePropertyException ex) { // expected } }
@Test public void nestedBindingWithDefaultConversionNoErrors() throws Exception { FieldAccessBean rod = new FieldAccessBean(); DataBinder binder = new DataBinder(rod, "person"); assertTrue(binder.isIgnoreUnknownFields()); binder.initDirectFieldAccess(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue(new PropertyValue("spouse.name", "Kerry")); pvs.addPropertyValue(new PropertyValue("spouse.jedi", "on")); binder.bind(pvs); binder.close(); assertEquals("Kerry", rod.getSpouse().getName()); assertTrue((rod.getSpouse()).isJedi()); }
@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 testCustomEditorWithBeanReference() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); lbf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() { @Override public void registerCustomEditors(PropertyEditorRegistry registry) { NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN); registry.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, nf, true)); } }); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("myFloat", new RuntimeBeanReference("myFloat")); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.setPropertyValues(pvs); lbf.registerBeanDefinition("testBean", bd); lbf.registerSingleton("myFloat", "1,1"); TestBean testBean = (TestBean) lbf.getBean("testBean"); assertTrue(testBean.getMyFloat().floatValue() == 1.1f); }
@Test public void testCustomEditorConfigurerWithEditorAsClass() throws ParseException { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); CustomEditorConfigurer cec = new CustomEditorConfigurer(); Map<Class<?>, Class<? extends PropertyEditor>> editors = new HashMap<Class<?>, Class<? extends PropertyEditor>>(); editors.put(Date.class, MyDateEditor.class); cec.setCustomEditors(editors); cec.postProcessBeanFactory(bf); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("date", "2.12.1975"); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.setPropertyValues(pvs); bf.registerBeanDefinition("tb", bd); TestBean tb = (TestBean) bf.getBean("tb"); DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN); assertEquals(df.parse("2.12.1975"), tb.getDate()); }
/** * Merge URI variables into the property values to use for data binding. */ @Override @SuppressWarnings("unchecked") protected void addBindValues(MutablePropertyValues mpvs, ServletRequest request) { String attr = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE; Map<String, String> uriVars = (Map<String, String>) request.getAttribute(attr); if (uriVars != null) { for (Entry<String, String> entry : uriVars.entrySet()) { if (mpvs.contains(entry.getKey())) { logger.warn("Skipping URI variable '" + entry.getKey() + "' since the request contains a bind value with the same name."); } else { mpvs.addPropertyValue(entry.getKey(), entry.getValue()); } } } }
@Test public void testAmountWithNumberFormat5() { FormattedMoneyHolder5 bean = new FormattedMoneyHolder5(); DataBinder binder = new DataBinder(bean); binder.setConversionService(conversionService); MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("amount", "USD 10.50"); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("USD 010.500", binder.getBindingResult().getFieldValue("amount")); assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d); assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode()); LocaleContextHolder.setLocale(Locale.CANADA); binder.bind(propertyValues); LocaleContextHolder.setLocale(Locale.US); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("USD 010.500", binder.getBindingResult().getFieldValue("amount")); assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d); assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode()); }
@Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { if (!this.isRegister()) { return; } ConfigurableListableBeanFactory factory = ((ConfigurableListableBeanFactory) beanFactory); for (String beanName : factory.getBeanDefinitionNames()) { BeanDefinition beanDefinition = factory.getBeanDefinition(beanName); boolean isHandlerMapping = isHandlerMapping(beanDefinition); if (isHandlerMapping) { // System.out.println("setBeanFactory postProcessBeanFactory BeanClassName:" + beanDefinition.getBeanClassName() + " class:" + this.getClass().getName()); MutablePropertyValues propertyValues = beanDefinition.getPropertyValues(); propertyValues.addPropertyValue("interceptors", this); } } }
@Override public BeanDefinition parse(Element element, ParserContext parserContext) { FieldDefine fieldDefine = parseFieldDefine(element); String id = fieldDefine.getId(); if (StringUtils.isEmpty(id)) { id = fieldDefine.toString()+"-"+System.currentTimeMillis(); } RootBeanDefinition beanDefinition = new RootBeanDefinition(); beanDefinition.setBeanClass(FieldDefine.class); beanDefinition.setLazyInit(false); BeanDefinitionRegistry registry = parserContext.getRegistry(); if (registry.containsBeanDefinition(id)) { throw new IllegalStateException("Duplicate spring bean id " + id); } registry.registerBeanDefinition(id, beanDefinition); MutablePropertyValues propertyValues = beanDefinition.getPropertyValues(); propertyValues.addPropertyValue("id", id); propertyValues.addPropertyValue("name", fieldDefine.getName()); propertyValues.addPropertyValue("type", fieldDefine.getType()); propertyValues.addPropertyValue("selector", fieldDefine.getSelector()); propertyValues.addPropertyValue("processor", fieldDefine.getProcessor()); propertyValues.addPropertyValue("defines", fieldDefine.getDefines()); return beanDefinition; }
@Override protected Object loadRepresentation(final InputStream in) throws IOException { final Properties props = (Properties) super.loadRepresentation(in); final Object bean = instantiateBean(); new BeanWrapperImpl(bean).setPropertyValues(new MutablePropertyValues(props), false); return bean; }
/** * @see org.springframework.beans.factory.config.BeanFactoryPostProcessor#postProcessBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) */ @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { ParameterCheck.mandatory("beanName", beanName); ParameterCheck.mandatory("extendingBeanName", extendingBeanName); // check for bean name if (!beanFactory.containsBean(beanName)) { throw new NoSuchBeanDefinitionException("Can't find bean '" + beanName + "' to be extended."); } // check for extending bean if (!beanFactory.containsBean(extendingBeanName)) { throw new NoSuchBeanDefinitionException("Can't find bean '" + extendingBeanName + "' that is going to extend original bean definition."); } // get the bean definitions BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); BeanDefinition extendingBeanDefinition = beanFactory.getBeanDefinition(extendingBeanName); // update class if (StringUtils.isNotBlank(extendingBeanDefinition.getBeanClassName()) && !beanDefinition.getBeanClassName().equals(extendingBeanDefinition.getBeanClassName())) { beanDefinition.setBeanClassName(extendingBeanDefinition.getBeanClassName()); } // update properties MutablePropertyValues properties = beanDefinition.getPropertyValues(); MutablePropertyValues extendingProperties = extendingBeanDefinition.getPropertyValues(); for (PropertyValue propertyValue : extendingProperties.getPropertyValueList()) { properties.add(propertyValue.getName(), propertyValue.getValue()); } }
/** * 向spring中注入dao代理 * @param beanFactory */ private void registryMangoDao(DefaultListableBeanFactory beanFactory){ for (Class<?> daoClass : findMangoDaoClasses(config.getScanPackage())) { GenericBeanDefinition bf = new GenericBeanDefinition(); bf.setBeanClassName(daoClass.getName()); MutablePropertyValues pvs = bf.getPropertyValues(); pvs.addPropertyValue("daoClass", daoClass); bf.setBeanClass(factoryBeanClass); bf.setPropertyValues(pvs); bf.setLazyInit(false); beanFactory.registerBeanDefinition(daoClass.getName(), bf); } }
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { MutablePropertyValues newprops = new MutablePropertyValues(pvs); for (PropertyDescriptor pd : pds) { ServiceReference s = hasServiceProperty(pd); if (s != null && !pvs.contains(pd.getName())) { try { if (logger.isDebugEnabled()) logger.debug("Processing annotation [" + s + "] for [" + beanName + "." + pd.getName() + "]"); FactoryBean importer = getServiceImporter(s, pd.getWriteMethod(), beanName); // BPPs are created in stageOne(), even though they are run in stageTwo(). This check means that // the call to getObject() will not fail with ServiceUnavailable. This is safe to do because // ServiceReferenceDependencyBeanFactoryPostProcessor will ensure that mandatory services are // satisfied before stageTwo() is run. if (bean instanceof BeanPostProcessor) { ImporterCallAdapter.setCardinality(importer, Availability.OPTIONAL); } newprops.addPropertyValue(pd.getName(), importer.getObject()); } catch (Exception e) { throw new FatalBeanException("Could not create service reference", e); } } } return newprops; }
private AbstractBeanDefinition createBeanReferenceDefinition(String beanName, BeanDefinition actualDef) { GenericBeanDefinition def = new GenericBeanDefinition(); def.setBeanClass(BeanReferenceFactoryBean.class); def.setAttribute(GENERATED_REF, Boolean.TRUE); def.setOriginatingBeanDefinition(actualDef); def.setDependsOn(new String[] { beanName }); def.setSynthetic(true); MutablePropertyValues mpv = new MutablePropertyValues(); mpv.addPropertyValue(TARGET_BEAN_NAME_PROP, beanName); def.setPropertyValues(mpv); return def; }