请简述@Autowired注解与@Resources注解的不同之处。
时间: 2023-03-24 17:03:31 浏览: 153
@Autowired注解和@Resources注解都是用于依赖注入的注解,但它们有一些不同之处。@Autowired注解是Spring框架提供的,它可以自动装配一个bean,可以根据类型、名称、注解等方式进行匹配。而@Resources注解是Java EE提供的,它可以注入一个指定名称的bean,可以根据名称进行匹配。此外,@Autowired注解默认是按照类型进行匹配,如果有多个类型相同的bean,则需要使用@Qualifier注解指定具体的bean。而@Resources注解则只能按照名称进行匹配。
相关问题
简述MyBatis利用注解开发步骤
MyBatis通过注解可以简化持久层代码的编写,其利用注解开发步骤主要包括以下几步:
1. **引入依赖**:首先,在项目中添加MyBatis及其支持注解的依赖,如mybatis-annotation。
2. **创建Mapper接口**:在Java接口中定义SQL操作,每个方法对应一条数据库查询或更新操作。例如:
```java
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User getUser(int id);
}
```
这里`@Mapper`注解表示这是个Mapper接口,`@Select`用于标记查询方法。
3. **映射文件**:在resources目录下创建mapper文件夹,并在其中生成XML文件(MyBatis的传统方式),或者在对应的mappers包下创建XML文件,配置SQL与接口方法的对应关系。
4. **配置MyBatis**:在Spring Boot项目中,通常在application.properties或yml文件中配置MyBatis的相关属性,比如数据源、mapper扫描路径等。
5. **注入Mapper**:在需要使用的业务模块中,通过@Autowired或者SqlSession工厂的方式注入对应的Mapper接口实例。
6. **调用Mapper方法**:在代码中可以直接调用接口方法执行SQL操作,无需手动拼接SQL。
2. 整合实例题目:设计一个基于SSM框架的学生信息管理系统,要求实现学生信息的增加、删除、修改和查询功能。请简述你的设计思路,包括如何整合Spring、SpringMVC和MyBatis来实现这些功能,并指出在整合过程中如何体现SSM的整合思想。代码怎么写
设计一个基于SSM框架的学生信息管理系统是一个典型的Web应用开发任务。SSM框架指的是Spring、SpringMVC和MyBatis的整合。下面我将简述设计思路,并指出如何整合这些框架来实现学生信息的增加、删除、修改和查询功能。
### 设计思路
1. **需求层(Controller)**:
- 使用SpringMVC来处理HTTP请求。
- 定义RESTful风格的接口来处理学生信息的增删改查操作。
2. **业务逻辑层(Service)**:
- 使用Spring来管理业务逻辑。
- 定义接口和实现类来处理具体的业务逻辑。
3. **数据访问层(DAO)**:
- 使用MyBatis进行数据库操作。
- 定义Mapper接口和对应的XML文件来映射SQL语句。
4. **数据库层**:
- 使用MySQL数据库来存储学生信息。
- 设计学生信息表(Student)来存储相关数据。
### 整合思路
1. **依赖管理**:
- 使用Maven来管理项目依赖,引入Spring、SpringMVC、MyBatis及相关依赖。
2. **配置文件**:
- 配置文件包括Spring的配置文件(applicationContext.xml)、SpringMVC的配置文件(spring-mvc.xml)和MyBatis的配置文件(mybatis-config.xml)。
- 在Spring的配置文件中配置数据源、事务管理和MyBatis的SqlSessionFactory。
- 在SpringMVC的配置文件中配置视图解析器、静态资源处理等。
3. **注解驱动**:
- 使用注解来简化配置,例如使用`@Controller`来标识控制器类,使用`@Service`来标识服务类,使用`@Repository`来标识DAO类。
### 代码示例
#### 1. Maven依赖配置(pom.xml)
```xml
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.10</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!-- JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
```
#### 2. Spring配置文件(applicationContext.xml)
```xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 扫描包 -->
<context:component-scan base-package="com.example.student" />
<!-- 数据源配置 -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/studentdb?useSSL=false&serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
<!-- SqlSessionFactory配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
<!-- MyBatis Mapper扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.student.dao" />
</bean>
<!-- 事务管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
```
#### 3. SpringMVC配置文件(spring-mvc.xml)
```xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描包 -->
<context:component-scan base-package="com.example.student.controller" />
<!-- 注解驱动 -->
<mvc:annotation-driven />
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 静态资源处理 -->
<mvc:resources mapping="/resources/**" location="/resources/" />
</beans>
```
#### 4. MyBatis配置文件(mybatis-config.xml)
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias type="com.example.student.model.Student" alias="Student" />
</typeAliases>
</configuration>
```
#### 5. 学生信息实体类(Student.java)
```java
package com.example.student.model;
public class Student {
private int id;
private String name;
private int age;
private String gender;
// Getters and Setters
}
```
#### 6. DAO接口(StudentDao.java)
```java
package com.example.student.dao;
import com.example.student.model.Student;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface StudentDao {
@Select("SELECT * FROM Student")
List<Student> getAllStudents();
@Select("SELECT * FROM Student WHERE id = #{id}")
Student getStudentById(int id);
@Insert("INSERT INTO Student(name, age, gender) VALUES(#{name}, #{age}, #{gender})")
void addStudent(Student student);
@Update("UPDATE Student SET name=#{name}, age=#{age}, gender=#[gender} WHERE id=#{id}")
void updateStudent(Student student);
@Delete("DELETE FROM Student WHERE id = #{id}")
void deleteStudent(int id);
}
```
#### 7. 服务接口(StudentService.java)
```java
package com.example.student.service;
import com.example.student.model.Student;
import java.util.List;
public interface StudentService {
List<Student> getAllStudents();
Student getStudentById(int id);
void addStudent(Student student);
void updateStudent(Student student);
void deleteStudent(int id);
}
```
#### 8. 服务实现类(StudentServiceImpl.java)
```java
package com.example.student.service.impl;
import com.example.student.dao.StudentDao;
import com.example.student.model.Student;
import com.example.student.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
@Override
public List<Student> getAllStudents() {
return studentDao.getAllStudents();
}
@Override
public Student getStudentById(int id) {
return studentDao.getStudentById(id);
}
@Override
public void addStudent(Student student) {
studentDao.addStudent(student);
}
@Override
public void updateStudent(Student student) {
studentDao.updateStudent(student);
}
@Override
public void deleteStudent(int id) {
studentDao.deleteStudent(id);
}
}
```
#### 9. 控制器(StudentController.java)
```java
package com.example.student.controller;
import com.example.student.model.Student;
import com.example.student.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/students")
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping
public String listStudents(Model model) {
List<Student> students = studentService.getAllStudents();
model.addAttribute("students", students);
return "studentList";
}
@GetMapping("/{id}")
public String getStudent(@PathVariable int id, Model model) {
Student student = studentService.getStudentById(id);
model.addAttribute("student", student);
return "studentDetail";
}
@GetMapping("/new")
public String newStudentForm(Model model) {
model.addAttribute("student", new Student());
return "studentForm";
}
@PostMapping
public String addStudent(@ModelAttribute Student student) {
studentService.addStudent(student);
return "redirect:/students";
}
@GetMapping("/edit/{id}")
public String editStudentForm(@PathVariable int id, Model model) {
Student student = studentService.getStudentById(id);
model.addAttribute("student", student);
return "studentForm";
}
@PutMapping("/{id}")
public String updateStudent(@PathVariable int id, @ModelAttribute Student student) {
student.setId(id);
studentService.updateStudent(student);
return "redirect:/students";
}
@DeleteMapping("/{id}")
public String deleteStudent(@PathVariable int id) {
studentService.deleteStudent(id);
return "redirect:/students";
}
}
```
### 总结
通过上述设计思路和代码示例,我们可以实现一个基于SSM框架的学生信息管理系统。Spring负责管理Bean,SpringMVC处理HTTP请求,MyBatis进行数据库操作。整合过程中,我们使用注解和配置文件来简化配置,实现了各层之间的松耦合。
阅读全文
相关推荐










