本例子主要模拟的是Spring的IOC功能,不含AOP
首先定义例子用到的entity,dao,service包下的类
Student类
public class Student {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
StudentDaoImpl类
public class StudentDaoImpl implements StudentDao {
@Override
public void add(Student stus) {
System.out.println("学生保存成功");
}
}
StudentServiceImpl类
public class StudentServiceImpl implements StudentService {
private StudentDao sdao;
public void setStudao(StudentDao sdao) {
this.sdao = sdao;
}
@Override
public void add(Student stu) {
sdao.add(stu);
}
}
ClassPathXmlApplicationContext容器类
public class ClassPathXmlApplicationContext implements BeanFactory {
private Map<String,Object> beans=new HashMap<String,Object>();
public ClassPathXmlApplicationContext() throws Exception, IOException {
SAXBuilder sb=new SAXBuilder();
Document doc=sb.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml"));
Element root=doc.getRootElement();
List list=root.getChildren("bean");
for(int i=0;i<list.size();i++){
Element ele=(Element) list.get(i);
String id=ele.getAttributeValue("id");
String clazz=ele.getAttributeValue("class");
Object o=Class.forName(clazz).newInstance();
beans.put(id, o);
for(Element proele:(List<Element>)ele.getChildren("property")){
String name =proele.getAttributeValue("name");
String bean=proele.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 id) {
return beans.get(id);
}
}
beans.xml
<beans>
<bean id="studao" class="com.wulijian.daoImpl.StudentDaoImpl"/>
<bean id="stuService" class="com.wulijian.ServiceImpl.StudentServiceImpl">
<property name="studao" bean="studao"/>
</bean>
</beans>
测试类
public class Test {
public static void main(String[] args) throws IOException, Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
Student stu = new Student();
StudentService service = (StudentService) context.getBean("stuService");
service.add(stu);
}
}