Skip to content

Commit ed8fe14

Browse files
committed
属性注入
1 parent c452019 commit ed8fe14

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

springBoot3/spring6/spring6-reflect/src/main/java/com/luojia/bean/AnnotationApplicationContext.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
package com.luojia.bean;
22

33
import com.luojia.anotation.Bean;
4+
import com.luojia.anotation.Di;
45

56
import java.io.File;
67
import java.io.IOException;
8+
import java.lang.reflect.Field;
79
import java.lang.reflect.InvocationTargetException;
810
import java.net.URL;
911
import java.net.URLDecoder;
1012
import java.util.Enumeration;
1113
import java.util.HashMap;
1214
import java.util.Map;
15+
import java.util.Set;
1316

1417
public class AnnotationApplicationContext implements MyApplicationContext{
1518

@@ -57,6 +60,9 @@ public AnnotationApplicationContext(String basePackage) {
5760
} catch (IllegalAccessException e) {
5861
throw new RuntimeException(e);
5962
}
63+
64+
// 属性注入
65+
loadDi();
6066
}
6167

6268
// 包扫描过程,实例化
@@ -109,6 +115,43 @@ public void loadBean(File file) throws ClassNotFoundException, NoSuchMethodExcep
109115
}
110116
}
111117

118+
// 属性注入
119+
private void loadDi() {
120+
// 实例化对象在 beanFactory 的map 集合里面
121+
// 1.遍历 beanFactory 的map集合
122+
Set<Map.Entry<Class, Object>> entries = beanFactory.entrySet();
123+
for (Map.Entry<Class, Object> entry : entries) {
124+
// 2.获取 map 集合每个对象(value),每个对象的属性都获取到
125+
Object obj = entry.getValue();
126+
Class<?> clazz = obj.getClass();
127+
128+
// 获取每个对象属性
129+
Field[] declaredFields = clazz.getDeclaredFields();
130+
// 3.遍历得到每个对象属性数组,得到每个属性
131+
for (Field field : declaredFields) {
132+
// 4.判断属性上是否有 @Di注解
133+
Di annotation = field.getAnnotation(Di.class);
134+
if (null != annotation) {
135+
// 如果私有属性,设置为可以设置值
136+
field.setAccessible(true);
137+
// 5.如果有 @Di 注解,把对象进行设置(注入)
138+
try {
139+
// set第一个参数是设置的对象,第二个事值,
140+
// 将字段类型取出,比如是service还是dao
141+
field.set(obj, beanFactory.get(field.getType()));
142+
} catch (IllegalAccessException e) {
143+
throw new RuntimeException(e);
144+
}
145+
}
146+
}
147+
148+
149+
}
150+
151+
152+
153+
}
154+
112155
public static void main(String[] args) {
113156

114157
}

0 commit comments

Comments
 (0)