package org.example; public interface StudentDao { void list(); void delete(int id); } package org.example; public interface StudentService { void list(); void delete(int id); } package org.example; import org.springframework.stereotype.Repository; @Repository("mockStudentDao") public class MockStudentDao implements StudentDao{ @Override public void list() { System.out.println("All students are listed in MockStudentDao."); } @Override public void delete(int id) { System.out.println("Student No."+id+"is deleted in MockStudentDao."); } } package org.example; import org.springframework.stereotype.Repository; @Repository("myBatisStudentDao") public class MyBatisStudentDao implements StudentDao{ @Override public void list() { System.out.println("All students are listed in MyBatisStudentDao."); } @Override public void delete(int id) { System.out.println("Student No."+id+"is deleted in MyBatisStudentDao."); } } package org.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @Service("studentServiceImpl") public class StudentServiceImpl implements StudentService{ private final StudentDao studentDao; @Autowired public StudentServiceImpl(@Qualifier("myBatisStudentDao")StudentDao studentDao){ this.studentDao=studentDao; } @Override public void list() { this.studentDao.list(); } @Override public void delete(int id) { this.studentDao.delete(id); } } package org.example; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); StudentService studentService = (StudentService) ctx.getBean("studentServiceImpl"); studentService.list(); studentService.delete(10); } }
时间: 2023-06-20 20:07:51 浏览: 122
StudentDAO.rar_StudentDao
这是一个使用 Spring 框架的 Java 代码示例,它实现了一个基本的三层架构,包括 DAO 层、Service 层和主函数入口。
其中,StudentDao 接口定义了两个方法:list() 和 delete(int id)。两个实现类 MockStudentDao 和 MyBatisStudentDao 分别实现了这两个方法。
StudentService 接口也定义了两个方法:list() 和 delete(int id)。StudentServiceImpl 实现了 StudentService 接口,并且它通过构造函数注入的方式,将 MyBatisStudentDao 对象注入到了 studentDao 属性中。
在 Main 类的 main 方法中,先通过 ClassPathXmlApplicationContext 加载了 beans.xml 配置文件,然后从中获取了 StudentService 对象,并且调用了它的 list() 和 delete(10) 方法。
这段代码是一个典型的基于 Spring 的三层架构的实现示例,它通过依赖注入的方式解耦了各个层之间的依赖关系,让代码更加灵活可维护。
阅读全文