基于注解的依赖注入方式实现学生信息新增。
1. 创建项目
Idea创建Java项目,项目名称为:case04-spring-student03。
2. 导入spring相关jar包
case04-spring-student03项目下创建lib目录,在lib目录下导入Jar包:
-
核心包
spring-core-5.3.25.jar
spring-beans-5.3.25.jar
spring-context-5.3.25.jar
spring-expression-5.3.25.jar
-
AOP包
spring-aop-5.3.25.jar
-
测试包
junit-4.6.jar
-
依赖包
commons-logging-1.2.jar
3. 创建Spring配置文件
src目录下创建applicationContext.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.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="com.wfit"/>
</beans>
4. 创建StudentService接口
src目录下创建com.wfit.service包,此包目录下创建StudentService接口,声明addStudent方法。
public interface StudentService {
//新增学生信息
public void addStudent();
}
5.创建StudentServiceImpl实现类
src目录下创建com.wfit.service.impl包,此包目录下创建StudentServiceImpl实现类,实现addStudent方法。
@Service //标注业务逻辑组件
public class StudentServiceImpl implements StudentService {
@Autowired //@Autowired注解 完成自动配置
private StudentDao studentDao;
@Override
public void addStudent() {
//调用StudentDao中的saveStudent方法
studentDao.saveStudent();
}
}
6. 创建StudentDao类
com.wfit.dao目录下创建StudentDao.java类
@Repository //标注数据访问层
public class StudentDao {
//保存学生信息
public void saveStudent(){
System.out.println("保存学生信息成功!");
}
}
7. 创建测试类
src目录下创建com.wfit.test包,此包目录下创建TestStudent测试类。
public class TestStudent {
@Test
public void test(){
//初始化Spring容器ApplicationContext,加载配置文件
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
//通过容器获取StudentServiceImpl实例
StudentService studentService =
applicationContext.getBean("studentServiceImpl",StudentService.class);
studentService.addStudent();
}
}