简单实现 spring 的 ioc

这周碰巧讨论到 spring 中的 ioc 于是趁有周末写写相关内容吧
项目已放入 Github

IOC 有什么作用?

当我们需要 new 一个对象时,直接调用 spring 的 bean 工厂就可以获取到我们需要的对象

实现思路

将需要注入的对象定义在外部文件中(xml),不过我是用 json 就是了,毕竟 xml 不熟悉 )
让 spring 对其解析,通过反射生成实例,然后调用其 set 方法将属性注入

example

xml 文件 applicationContext.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[
{
"id": "user",
"class": "web.entity.User"
},
{
"id": "userDAO",
"class": "web.dao.impl.UserDAOImpl"
},
{
"id": "userService",
"class": "web.service.impl.UserServiceImpl",
"property":[
{
"name": "userDAO",
"ref": "userDAO"
}
]
}
]

User

1
2
3
4
5
6
7
8
9
10
11
public class User {
private String uname;
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
}

UserDao

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public interface UserDAO {
User findUser();
void update(User user);
}
public class UserDAOImpl implements UserDAO {
@Override
public User findUser() {
User user = new User();
user.setUname("hello world");
return user;
}
@Override
public void update(User user) {
System.out.println("***** update ***** : " + user.getUname());
}
}

UserService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public interface UserService {
User findUser();
void update(User user);
}
public class UserServiceImpl implements UserService {
private UserDAO userDAO;
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
@Override
public User findUser() {
return userDAO.findUser();
}
@Override
public void update(User user) {
userDAO.update(user);
}
}

ClassPathJsonApplicationContext

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
public class ClassPathJSONApplicationContext implements BeanFactory {
private List<Map<String, Object>> listMap;
private Map<String, Object> sigletions = new HashMap<String, Object>();
public ClassPathJSONApplicationContext(String path) {
this.scanJson(path);
this.instantiation();
}
private void instantiation() {
for (Map<String, Object> map : listMap) {
try {
String beanId = (String) map.get("id");
String clzss = (String) map.get("class");
Object o = Class.forName(clzss).newInstance();
sigletions.put(beanId, o);
// System.out.println(sigletions);
List<Map<String,Object>> propertyList = (List<Map<String, Object>>) map.get("property");
if (propertyList != null) {
for (Map<String, Object> property : propertyList) {
String name = (String) property.get("name");
String ref = (String) property.get("ref");
Object beanObj =this.sigletions.get(ref);
String methodName = "set" + name.substring(0, 1).toUpperCase()
+ name.substring(1);
Method m = o.getClass().getMethod(methodName,
beanObj.getClass().getInterfaces()[0]);
m.invoke(o, beanObj);
// System.out.println(methodName);
}
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
private void scanJson(String path) {
StringBuilder sb = new StringBuilder();
File file = new File(path);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
while ((tempString = reader.readLine()) != null){
sb.append(tempString + "\n");
line++;
}
listMap = JSON.parseObject(sb.toString(), new TypeReference<List<Map<String,Object>>>(){});
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null){
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
@Override
public Object getBean(String name) {
return sigletions.get(name);
}
}

UserController

1
2
3
4
5
6
7
8
9
10
11
12
13
public class UserController {
@Test
public void updateUserName() {
BeanFactory factory = new ClassPathJSONApplicationContext("src/main/resources/bean.json");
UserService userService = (UserService) factory.getBean("userService");
User user = userService.findUser();
System.out.println(user.getUname());
user.setUname("Lee");
userService.update(user);
}
}

0%