要求:假设通过StudentController、StudentService和StudentDao等类和接口完成学生的保存操作,请编程实现相关的接口和类,要求采用Spring框架技术中提供的控制反转和依赖注入的松耦合编程方法,使用基于Annotation的Bean装配方法来实现相关组件的生成,写出测试程序,运行查看其结果。
要使用Spring框架对类和对象进行管理,关键在于配置环境
1、导入所需要的jar包
将Spring的四个核心包,一个依赖包,还有实现包扫描需要用到的aop的包复制到lib目录下
2、StudentDao接口
package experiment01;
public interface StudentDao {
public void save();
}
3、StudentDaoImpl实现类
package experiment01;
import org.springframework.stereotype.Repository;
@Repository("studentDao")
public class StudentDaoImpl implements StudentDao{
public void save(){
System.out.println("studentDao...save...");
}
}
4、StudentService接口
package experiment01;
public interface StudentService {
public void save();
}
5、StudentServiceImpl实现类
package experiment01;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
@Service("studentService")
public class StudentServiceImpl implements StudentService{
@Resource(name="studentDao")
StudentDao studentDao;
public void save(){
this.studentDao.save();
System.out.println("studentService...save...");
}
}
6、StudentController控制器类
package experiment01;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller("studentController")
public class StudentController {
@Autowired
StudentService studentService;
public void save(){
this.studentService.save();
System.out.println("studentController...save...");
}
}
7、配置文件beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!--有两种方式进行注解配置 -->
<!-- 第一种 利用context:annotation-config一个一个配置注解 -->
<context:annotation-config />
<bean id="studentDao" class="experiment01.StudentDaoImpl"/>
<bean id="studentService" class="experiment01.StudentServiceImpl"/>
<bean id="studentController" class="experiment01.StudentController"/>
<!-- 第二种 利用包扫描 -->
<!--
<context:component-scan base-package="experiment01"/>
-->
</beans>
8、编写测试类
package experiment01;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AnnotationTest {
public static void main(String[] args) {
//定义配置文件的路径;
String xmlPath="experiment01/beans1.xml";
//创建Spring的ApplicationContext容器;
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
//通过获取容器内的bean得到StudentController对象;
StudentController studentController=(StudentController)applicationContext.getBean("studentController");
//调用StudentController对象的方法;
studentController.save();
}
}
运行结果: