面向接口编程调试方便
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="stu1" className="my.domain.Student">
<property name="name" value="zhangSan"/>
<property name="age" value="11" />
<property name="sex" value="男"/>
<property name="teacher" ref="t1"/><!-- ref的值必须是另一个bean的id -->
</bean>
<bean id="stu2" className="my.domain.Student">
<property name="name" value="wangWu"/>
<property name="age" value="13" />
<property name="sex" value="男"/>
<property name="teacher" ref="t1"/><!-- ref的值必须是另一个bean的id -->
</bean>
<bean id="t1" className="my.domain.Teacher">
<property name="name" value="lisi"/>
<property name="age" value="11" />
<property name="salaray" value="2000"/>
</bean>
<bean id="stuDao" className="my.dao.impl.StudentImpl"></bean>
<bean id="stuService" className="my.service.impl.StudentServiceImpl">
<property name="studentDao" ref="stuDao"/>
</bean>
</beans>
public interface StudentDao {
void add(Student stu);
void update(Student stu);
}
public class StudentImpl implements StudentDao {
@Override
public void add(Student stu) {
System.out.println("StudentImpl.add()");
}
@Override
public void update(Student stu) {
System.out.println("StudentImpl.update()");
}
}
public class StudetnServiceImpl implements StudentService {
private StudentDao studentDao = null;
//谁调用service方法,谁就需要先调用这个方法,提供dao
public void setStudentDao(StudentDao studentDao){
}
@Override
public void login() {
studentDao.add(null);
studentDao.update(null);
}
}
/*
* 面向接口编程
* dao
* daoImpl
* service
* serviceImpl
*/
public class Demo1 {
@Test
public void fun1(){
// Student stu = new Student();
/*
* 1、创建Bean工厂,创建时需要给工厂指定配置文件
* 2、从工厂中获取bean对象
*/
BeanFactory bf = new BeanFactory("beans.xml");
Student s1 = bf.getBean("stu1");
Student s2 = bf.getBean("stu1");
System.out.println(s1==s2);//单例
}
public void fun2(){
// Student stu = new Student();
/*
* 1、创建Bean工厂,创建时需要给工厂指定配置文件
* 2、从工厂中获取bean对象
*/
BeanFactory bf = new BeanFactory("beans.xml");
Student s1 = bf.getBean("stu1");
Student s2 = bf.getBean("stu2");
System.out.println(s1.getTeacher()==s2.getTeacher());//单例
}
@Test
public void fun3(){
BeanFactory bf = new BeanFactory("beans.xml");
// StudentImpl stuImpl = (StudentImpl)bf.getBean("stuDao");
StudentDao stuDao = (StudentDao) bf.getBean("stuDao");
stuDao.add(null);
stuDao.update(null);
}
public void fun4(){
BeanFactory bf = new BeanFactory("beans.xml");
StudentService service = (StudentService) bf.getBean("stuService");
service.login();
}
}