C02_D10_Annotation_Autowired_exercise
//entity
/**
* *学生实体类,用于存储学生所有信息
*
* @author 22-426
*/
public class Student implements Serializable {
private String srollno;
private String sname;
private String sgender;
private String sbatch;
private String spassword;
public Student() {
}
public Student(String srollno, String sname, String spassword, String sgender, String sbatch) {
this.srollno = srollno;
this.sname = sname;
this.sgender = sgender;
this.sbatch = sbatch;
this.spassword = spassword;
}
public String getSrollno() {
return srollno;
}
public void setSrollno(String srollno) {
this.srollno = srollno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSgender() {
return sgender;
}
public void setSgender(String sgender) {
this.sgender = sgender;
}
public String getSbatch() {
return sbatch;
}
public void setSbatch(String sbatch) {
this.sbatch = sbatch;
}
public String getSpassword() {
return spassword;
}
public void setSpassword(String spassword) {
this.spassword = spassword;
}
@Override
public String toString() {
return srollno + "\t" + sname + "\t\t" + spassword + "\t\t" + sgender + "\t" + sbatch;
}
}
//dao&daoImpl
public interface StudentDao {
Student getOneStudent(String id);
}
//@Component注解可以将一个类注册为spring管理的bean
//但是spring专门为Dao类提供了一个相同功能的注解@Repository
@Repository
public class StudentDaoImpl implements StudentDao {
@Override
public Student getOneStudent(String id) {
System.out.println("......................调用了StudentDaoImpl的getOneStudent()方法......................");
return new Student("2018208888", "小明", "123456", "M", "18软件J01");
}
}
//service&serviceImpl
public interface StudentService {
void login(String id, String pwd);
}
//@Component注解可以将一个类注册为spring管理的bean
//但是spring专门为Service类提供了一个相同功能的注解@Service
@Service
public class StudentServiceImpl implements StudentService {
//自动装配的前提是两个bean(依赖的bean和被依赖的bean)都归spring容器管理
StudentDao studentDao;
//如果将@Autowired注解放在构造函数前,则spring容器调用构造函数实现自动装配
@Autowired
public StudentServiceImpl(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
public void login(String id, String pwd) {
System.out.println("......................调用了StudentServiceImpl的login()方法.................................");
Student s = studentDao.getOneStudent(id);
if (null != s && pwd.equals(s.getSpassword()))
System.out.println("学号和密码正确,登录成功~~~");
else
System.out.println("学号或密码错误,登录失败!!!");
}
}
//config-beans.xml
<!-- 开启包扫描,给对应的类加注解,注册为spring管理的bean -->
<!-- 并且使用@Autowired注解将StudentDao对象注入StudentServiceImpl中 -->
<!-- 扫描包可以指定多个包名,逗号隔开多个包名即可 -->
<context:component-scan base-package="com.qdu.service,com.qdu.dao">
</context:component-scan>
//main
public static void main(String[] args) {
ApplicationContext ctx=
new ClassPathXmlApplicationContext("config/beans.xml");
StudentService service=ctx.getBean(StudentService.class);
service.login("2018208888","123456");
}