三层架构的发展

MODEL  1:

        jsp    ----->     展示层     view  /  控制层  controller(JSP在此也肩有控制层的作用)

         ↓

     service  /  biz  /  manager     业务层

         ↓

        DAO            data   access  object 

         ↓

        DB

MODEL  1:此时的JSP不光管显示而且管控制,发现大项目需要跳转的页面过于多,单单靠JSP来进行页面跳转和控制不好维护,就有了MODEL  2

MODEL  2:                MVC         spring粘合剂(将层与层之间结合在一起)

        jsp    ----->     展示层     view

         ↓

     servlet             控制层      controller                         SpringMVC     struts

         ↓

     service  /  biz  /  manager     业务层

         ↓

        DAO            data   access  object         JDBC        MyBatis

         ↓

        DB

单项依赖(面向接口编程)(解耦)

注意:层与层之间做到单向依赖(dao影响不到service)

代码实现

public interface StudentDao {
 
    public void insert(Student student);
}
public class StudentDaoImpl implements StudentDao {

    public void insert(Student student){
        System.out.println("student dao impl");
    }

}
public interface StudentService {

    public void register(Student student);
}
public class StudentServiceImpl implements StudentService {

    //xml中进行配置,自动创建该对象(此对象在此处为一个属性)
    private  StudentDao studentDao;

    public StudentDao getStudentDao() {
        return studentDao;
    }

    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }

    public void register(Student student) {
        studentDao.insert(student);
    }
    
}

applicationContext.xml

<bean id = "studentDao" class ="com.spring.mvc.StudentDaoImpl">
    
</bean>

<bean id = "studentService" class ="com.spring.mvc.StudentServiceImpl">
    <property name = "studentDao" ref = "studentDao"></property>
</bean>
public class Client {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //此处为获取bean中的对象,第一个参数为bean中的id,第二个为对象类型
        StudentService studentService = context.getBean("studentService",StudentService.class);
        studentService.register(null);

    }
}

如果此时采用Oracle,dao层只需要改一下Impl,同样实现相同的dao接口,service中对象的创建只需要在xml中做修改即可

public class StudentDaoOracleImpl implements StudentDao {

    public void insert(Student student){
        System.out.println("student dao impl Oracle");
    }

}

applicationContext.xml

<bean id = "studentDao" class ="com.spring.mvc.StudentDaoImpl"></bean>

<bean id = "studentDaoOracle" class ="com.spring.mvc.StudentDaoImpl"></bean>


<bean id = "studentService" class ="com.spring.mvc.StudentServiceImpl">
    <property name = "studentDao" ref = "studentDaoOracle"></property>
</bean>

Client 类就无需做更改了!!!

这就体现出Spring的好处了~

个性签名:一个人在年轻的时候浪费自己的才华与天赋是一件非常可惜的事情

        如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!

万水千山总是情,打赏5毛买辣条行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾! 

猜你喜欢

转载自blog.csdn.net/qq_42000661/article/details/108150424