本内容采用最新SpringBoot3框架版本,视频观看地址:B站视频播放
1. Spring注解概述
在Spring框架中,尽管使用xml配置文件可以简单的装配Bean,但如果应用中有大量的Bean需要装配时,会导致xml配置文件过于庞大和繁重,影响开发效率,所以推荐使用注解(annotation)代替xml配置文件,可以简化配置,提高开发效率。
2. 声明Bean的注解
| 注解名称 | 注解说明 |
| @Component | 该注解是一个泛化的概念,表示一个组件对象(Bean) |
| @Controller | 标注一个控制器组件类(Spring MVC的Controller),其功能与@Conponent相同 |
| @Service | 标注一个业务逻辑组件类(Service层),其功能与@Component相同 |
| @Repository | 标注一个数据访问层(DAO)的类,其功能与@Component相同 |
3. 注入Bean的注解
| 注解名称 | 注解说明 |
| @Autowired | 该注解可以对类成员变量、方法、构造方法进行标注,完成自动配置工作,通过@Autowired可以自动完成getter、setter方法,默认按照Bean的类型进行装配 |
| @Resource | 该注解与@Autowired功能一样,区别在于该注解默认按照名称进行装配 |
| @Qualifier | 该注解与@Autowired注解配合使用,当@Autowired注解需要按照名称来装配注入时,则需要结合该注解一起使用,Bean的实例名称由Qualifier注解的参数指定 |
4. 基于注解的依赖注入方式实现学生信息新增案例
基于注解的依赖注入方式实现学生信息新增,具体要求如下:
- 项目名称为:spring-student02
- 使用Spring框架
- 创建StudentService接口,定义addStudent方法
- 创建StudentServiceImpl实现类,实现addStudent方法,调用StudentDao中的saveStudent方法
- 创建StudentDao类,实现saveStudent方法,输出“保存学生信息成功”
4.1 创建Java项目
Idea创建Java项目,项目名称为:spring-student02。
4.2 导入Spring核心Jar包
spring-student01项目下创建lib目录,在lib目录下导入Jar包:
核心包:
- spring-core-6.0.0-RC2.jar、
- spring-beans-6.0.0-RC2.jar、
- spring-context-6.0.0-RC2.jar、
- spring-expression-6.0.0-RC2.jar
AOP包:spring-aop-6.0.0-RC2.jar
依赖包:spring-jcl-6.0.0-RC2.jar
测试包:junit-4.6.jar
4.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.4 创建StudentDao类
com.wfit.dao目录下创建StudentDao.java类
@Repository //标注数据访问层
public class StudentDao {
//保存学生信息
public void saveStudent(){
System.out.println("保存学生信息成功!");
}
}
4.5 创建StudentService接口
com.wfit.service目录下创建StudentService接口,声明addStudent方法。
public interface StudentService {
//新增学生信息
public void addStudent();
}
4.6 创建StudentServiceImpl实现类
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();
}
}
4.7 创建测试类
com.wfit目录下创建TestStudent测试类。
public class TestStudent {
@Test
public void test(){
//初始化Spring容器ApplicationContext,加载配置文件
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
//通过容器获取StudentService实例
StudentService studentService = (StudentService)applicationContext.getBean("studentServiceImpl");
studentService.addStudent(); //调用addStudent方法
}
}
4.8 执行测试
在IDEA中启动TestStudent测试类,控制台会输出结果。