|
6 | 6 | import us.codecraft.tinyioc.beans.PropertyValue;
|
7 | 7 |
|
8 | 8 | import java.lang.reflect.Field;
|
| 9 | +import java.lang.reflect.Method; |
9 | 10 |
|
10 | 11 | /**
|
11 | 12 | * 可自动装配内容的BeanFactory
|
|
15 | 16 | public class AutowireCapableBeanFactory extends AbstractBeanFactory {
|
16 | 17 |
|
17 | 18 | protected void applyPropertyValues(Object bean, BeanDefinition mbd) throws Exception {
|
18 |
| - if (bean instanceof BeanFactoryAware){ |
19 |
| - ((BeanFactoryAware)bean).setBeanFactory(this); |
20 |
| - } |
| 19 | + if (bean instanceof BeanFactoryAware) { |
| 20 | + ((BeanFactoryAware) bean).setBeanFactory(this); |
| 21 | + } |
21 | 22 | for (PropertyValue propertyValue : mbd.getPropertyValues().getPropertyValues()) {
|
22 |
| - Field declaredField = bean.getClass().getDeclaredField(propertyValue.getName()); |
23 |
| - declaredField.setAccessible(true); |
24 | 23 | Object value = propertyValue.getValue();
|
25 | 24 | if (value instanceof BeanReference) {
|
26 | 25 | BeanReference beanReference = (BeanReference) value;
|
27 | 26 | value = getBean(beanReference.getName());
|
28 | 27 | }
|
29 |
| - declaredField.set(bean, value); |
| 28 | + |
| 29 | + try { |
| 30 | + Method declaredMethod = bean.getClass().getDeclaredMethod( |
| 31 | + "set" + propertyValue.getName().substring(0, 1).toUpperCase() |
| 32 | + + propertyValue.getName().substring(1), value.getClass()); |
| 33 | + declaredMethod.setAccessible(true); |
| 34 | + |
| 35 | + declaredMethod.invoke(bean, value); |
| 36 | + } catch (NoSuchMethodException e) { |
| 37 | + Field declaredField = bean.getClass().getDeclaredField(propertyValue.getName()); |
| 38 | + declaredField.setAccessible(true); |
| 39 | + declaredField.set(bean, value); |
| 40 | + } |
30 | 41 | }
|
31 | 42 | }
|
32 | 43 | }
|
0 commit comments