在Spring中 我们可以通过依赖注入 完成类之间的通信, SpringBoot则可以通过配置类 来实现我们所需要的功能。
我们以Service 调用 Dao 来做例子
//配置类
@Configuration
public class AppConfig {
@Bean //通过@bean来实现<bean>的功能
public StudentService studentService() { //等价<bean id="">
StudentService stuService= new StudentService();
StudentDao studentDao= new StudentDao();
stuService.setStudentDao(studentDao);
return stuService; //返回值 等价<bean class="">
}
@Bean StudentDao studentDao() {
StudentDao stuDao= new StudentDao();
return stuDao;
}
}
Service
@Component
public class StudentService {
private static StudentDao studentdao;
public StudentService() {
}
public StudentDao getStudentDao() {
return studentdao;
}
public void setStudentDao(StudentDao dao) {
this.studentdao = dao;
}
@Test
public void add() {
System.out.println("Service...");
}
}
Dao
@Component
public class StudentDao {
public StudentDao() {
}
@Test
public void add() {
System.out.println("Dao........");
}
}
测试
@Test
public void contextLoads() {
//System.out.println(student1);
StudentService service = new StudentService();
//StudentDao dao = new StudentDao();
//service.setStudentDao(dao);
service.add();
service.getStudentDao().add();
}