Ioc之全註解開發

文采杰出發表於2024-06-02
  • @Configuration是@Component的別名,所以兩個使用哪個都可以
  • @ComponentScan註解中value的別名是basePackages,所以兩個用哪個都可以
  • 配置類
@Component
//@Configuration
//@ComponentScan(value = {"cn.powernode.dao","cn.powernode.service"})
@ComponentScan(basePackages = {"cn.powernode.dao","cn.powernode.service"})
public class Spring6Config {
}

該配置類相當於*.xml配置檔案中的<context:component-scan base-package="org.powernode"/>

  • 持久層介面
public interface StudentDao {
    void deleteById();
}
  • 持久層實現類
//@Repository中預設的value也是類名首字母變小寫
@Repository("studentDaoImplForMySql")
public class StudentDaoImplForMySql implements StudentDao {
    @Override
    public void deleteById() {
        System.out.println("Mysql正在刪除學生資訊");
    }
}
  • 業務層
@Service(value = "studentService")
public class StudentService {

//    @Resource(name = "studentDaoImplForMySql")
    @Resource(name = "studentDaoImplForMySql")
    private StudentDao studentDao;

//    @Resource(name = "studentDaoImplForMySql")
    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }

    public void deleteStudent(){
        studentDao.deleteById();
    }
}
  • 測試
    @org.junit.Test
    public void testNoXml(){
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(Spring6Config.class);
        StudentService studentService = annotationConfigApplicationContext.getBean("studentService",StudentService.class);
        studentService.deleteStudent();
    }

相關文章