Ioc之全注解开发

  • @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();
    }
posted @ 2024-06-02 23:26  文采杰出  阅读(1)  评论(0编辑  收藏  举报