Sprig 之 模拟Spring IOC
IOC是Spring的核心,其他的我也不多说了,直接进入主题。
1. 创建实体类User.java
package com.zsw.spring.ioc;
public
class User {
private
int id;
private
String name;
private
String age;
// ….舍略getter/setter
}
2. 创建Dao层UserDao.java/UserDaoImpl.java
package com.zsw.spring.ioc;
public
interface UserDao {
public
void add();
}
package com.zsw.spring.ioc;
public
class UserDaoImpl
implements UserDao {
@Override
public
void add() {
}
}
3. 创建Service层UserService..java
package com.zsw.spring.ioc;
public
class UserService {
private UserDao userDao;
public
void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
4. 定义一个BeanFactory接口和Spring的取名一样
package com.zsw.spring.ioc;
public
interface BeanFactory {
public Object getBean(
String name);
}
5. 定义ClassPathXmlApplicationContext 实现BeanFactory接口
这也是和Spring中的取名相同,具体实现如下:
在初始化的时候读取配置文件,根据反射机制实例化相应的对象及注入相关的依赖对象。
package com.zsw.spring.ioc;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public
class ClassPathXmlApplicationContext
implements BeanFactory {
private Map<
String,Object> beans =
new HashMap<
String, Object>();
public ClassPathXmlApplicationContext()
throws
Exception{
SAXBuilder sb =
new SAXBuilder();
Document doc = sb.build(
this.getClass().getClassLoader().getResourceAsStream(
"bean.xml"));
Element root = doc.getRootElement();
//获取根元素
List list = (List) root.getChildren(
"bean");
//获取名字为bean的所有元素
for(
int i = 0;i<list.size();i++){
Element element = (Element)list.get(i);
String id = element.getAttributeValue(
"id");
String clazz = element.getAttributeValue(
"class");
System.out.println(id +
":" + clazz);
Object o = Class.forName(clazz).newInstance();
beans.put(id, o);
for(Element propertyElement : (List<Element>)element.getChildren(
"property")){
String name = propertyElement.getAttributeValue(
"name");
String bean = propertyElement.getAttributeValue(
"bean");
Object beanObject = beans.get(bean);
String methodName =
"set" + name.substring(0,1).toUpperCase() + name.substring(1);
System.out.println(
"method name = " + methodName);
Method m = o.getClass().getMethod(methodName,beanObject.getClass().getInterfaces()[0]);
m.invoke(o, beanObject);
}
}
}
@Override
public Object getBean(
String name) {
return beans.get(name);
}
}
6. 配置文件bean.xml如下:
<?xml version=
"1.0" encoding=
"UTF-8"?>
<beans>
<bean id=
"user"
class=
"com.zsw.spring.ioc.User" />
<bean id=
"userDao"
class=
"com.zsw.spring.ioc.UserDaoImpl"></bean>
<bean id=
"userService"
class=
"com.zsw.spring.ioc.UserService">
<property name=
"userDao" bean=
"userDao" />
</bean>
</beans>
7. 最后编写测试类
package com.zsw.spring.ioc;
public
class UserServiceTest {
public
static
void main(
String[] args)
throws
Exception {
BeanFactory factory =
new ClassPathXmlApplicationContext();
UserDao service = (UserDao) factory.getBean(
"userDao");
}
}