spring 中部分注解的使用
我们先解释一下IoC和DI
IoC:lOC: Inversion of Control,翻译过来是反转控制。把对象创建和对象之间的调用过程,交给 Spring 进行管理
DI:Dependency Injection 翻译过来是依赖注入,DI 是指在组件之间传递依赖关系的过程中,将依赖关系在容器内部进行处理,这样就不必在应用程序代码中硬编码对象之间的依赖关系,实现了对象之间的解耦合。在 Spring 中,DI 是通过 XML 配置文件或注解的方式实现的。它提供了三种形式的依赖注入:构造函数注入、Setter 方法注入和接口入。
下面我们来说一下使用xml配置的方式进行其依赖注入,和注解的方式进行实现吧
- 首先其方式,都得先进行依赖的导入
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.8.0-beta4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.8.0-beta4</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- 数据库驱动和连接池-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!-- spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies>
</project>
- 说到spring中的注解,那就不能只说其注解,应从对比xml配置文件开始说起,下面我们从xml文件的形式用代码进行说明一些用法(其中很多的用法未进行实现,这里我们只演示部分关于我们代码所用到的部分)
<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:property-placeholder location="jdbc.properties,student.properties" />
<!--
步骤1:需要连接数据库,并且创建druid数据连接池
-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${csi.driverClassName}" />
<property name="url" value="${csi.url}" />
<property name="username" value="${csi.username}" />
<property name="password" value="${csi.password}" />
</bean>
<!--
步骤2:创建一个JDBCTemplate对象
-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" scope="prototype">
<constructor-arg ref="dataSource" />
</bean>
<!--
步骤3:将jdbcTemplate注入到的属性中
未使用注解的方式
-->
<bean id="studentDao" class="com.csi.dao.impl.StudentDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<bean id="studentService" class="com.csi.service.impl.StudentServiceImpl">
<property name="studentDao" ref="studentDao" />
</bean>
<bean id="studentController" class="com.csi.controller.StudentController">
<property name="studentService" ref="studentService" />
</bean>
<!--
init-method:调用自定义的初始化方法
destroy-method:调用自定义销毁方法。
该方法需要使用容器的关闭方法,才能够看到。否则就要碰运气!
scope="prototype":代表每一次获取都会返回一个新的对象
scope="singleton":代表每一次返回的都是同一个对象
-->
<!-- <bean id="person" class="com.csi.domain.Person" scope="prototype" init-method="init" destroy-method="destroy" />-->
</beans>
这是通过xml文件进行Spring 注解的一个方式,实体类如下
package com.csi.domain;
import lombok.Data;
@Data
public class Student {
//id
private Integer id;
//姓名
private String name;
//性别
private String gender;
//年龄
private Integer age;
//班级
private String classes;
}
package com.csi.dao.impl;
import com.csi.dao.StudentDao;
import com.csi.domain.Student;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
public class StudentDaoImpl implements StudentDao {
private JdbcTemplate jdbcTemplate ;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public int save(Student student) {
String sql = "insert into students (id,name,gender,age,class) values (?,?,?,?,?)" ;
int ret=this.jdbcTemplate.update(sql,student.getId(),student.getName(),student.getGender(),student.getAge(),
student.getClasses());
return ret;
}
@Override
public int modify(Student student) {
String sql="update students set id=?,name=?,gender=?,age=?,class=? where id=?";
int ret=this.jdbcTemplate.update(sql,student.getId(),student.getName(),student.getGender(),student.getAge(),
student.getClasses(),student.getId());
return ret;
}
@Override
public List<Student> list() {
String sql="select id,name,gender,age,class from students";
// new BeanPropertyRowMapper<>(Student.class)
//这里是因为数据库中的字段名和我Java中使用的字段名的映射问题,所以使用了lamda表达式的方式进行字段的一一映射, 如果一直的话可使用以上的new BeanPropertyRowMapper<>(Student.class)的方式进行相应的映射,并进行读取
List<Student> list=this.jdbcTemplate.query(sql,(rs,rowNum) -> {
Student student = new Student() ;
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setGender(rs.getString("gender"));
student.setAge(rs.getInt("age"));
student.setClasses(rs.getString("class"));
return student ;
});
return list;
}
@Override
public Student findById(Integer id) {
String sql="select id,name,gender,age,class from students where id=?";
Student stu=this.jdbcTemplate.queryForObject(sql,(rs,rowNum) -> {
Student student = new Student() ;
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setGender(rs.getString("gender"));
student.setAge(rs.getInt("age"));
student.setClasses(rs.getString("class"));
return student ;
},id);
return stu;
}
@Override
public int deleteById(Integer id) {
String sql="delete from students where id=?";
int ret=this.jdbcTemplate.update(sql,id);
return ret;
}
}
package com.csi.service.impl;
import com.csi.dao.StudentDao;
import com.csi.domain.Student;
import com.csi.service.StudentService;
import org.springframework.stereotype.Service;
import java.util.List;
public class StudentServiceImpl implements StudentService {
private StudentDao studentDao ;
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
public int save(Student student) {
return this.studentDao.save(student);
}
@Override
public int modify(Student student) {
return this.studentDao.modify(student);
}
@Override
public List<Student> list() {
return this.studentDao.list();
}
@Override
public Student findById(Integer id) {
return this.studentDao.findById(id);
}
@Override
public int deleteById(Integer id) {
return this.studentDao.deleteById(id);
}
}
package com.csi.controller;
import com.csi.domain.Student;
import com.csi.service.StudentService;
import java.util.List;
public class StudentController {
private StudentService studentService ;
public void setStudentService(StudentService studentService) {
this.studentService = studentService;
}
public int save(Student student) {
return this.studentService.save(student);
}
public int modify(Student student) {
return this.studentService.modify(student);
}
public List<Student> list() {
return this.studentService.list();
}
public Student findById(Integer id) {
return this.studentService.findById(id);
}
public int deleteById(Integer id) {
return this.studentService.deleteById(id);
}
}
测试类
import com.csi.controller.StudentController;
import com.csi.domain.Student;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.swing.plaf.synth.SynthUI;
import java.util.List;
public class TestStudentController {
@Test
public void save(){
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml") ;
StudentController studentController = ctx.getBean(StudentController.class);
Student student=new Student();
student.setId(9);
student.setAge(20);
student.setName("钱十一");
student.setGender("男");
student.setClasses("高中三班");
studentController.save(student);
}
@Test
public void list(){
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml") ;
StudentController studentController = ctx.getBean(StudentController.class);
List<Student> list = studentController.list();
for (Student student : list) {
System.out.println(student);
}
}
@Test
public void findById(){
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml") ;
StudentController studentController = ctx.getBean(StudentController.class);
Student byId = studentController.findById(1);
System.out.println(byId);
}
@Test
public void deleteById(){
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml") ;
StudentController studentController = ctx.getBean(StudentController.class);
int ret=studentController.deleteById(9);
System.out.println(ret);
}
@Test
public void modify(){
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml") ;
StudentController studentController = ctx.getBean(StudentController.class);
Student student=new Student();
student.setId(1);
student.setAge(20);
student.setName("张三");
student.setGender("女");
student.setClasses("高中三班");
int ret=studentController.modify(student);
System.out.println(ret);
}
}
- 下面是使用注解方式进行的;
<?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:property-placeholder location="jdbc.properties,student.properties" />
<!-- 扫描文件-->
<!-- 注解使用方式-->
<context:component-scan base-package="com.csi">
<!-- 指定扫描文件-->
<!-- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
<!-- 指定不扫描文件-->
<!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
</context:component-scan>
<!--
步骤1:需要连接数据库,并且创建druid数据连接池
-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${csi.driverClassName}" />
<property name="url" value="${csi.url}" />
<property name="username" value="${csi.username}" />
<property name="password" value="${csi.password}" />
</bean>
<!--
步骤2:创建一个JDBCTemplate对象
-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" scope="prototype">
<constructor-arg ref="dataSource" />
</bean>
</beans>
从xml文件看,其减少了一些依赖注入的配置代码,在后续会使用一些注解进行依赖注入操作
package com.csi.dao.impl;
import com.csi.dao.StudentDao;
import com.csi.domain.Student;
import com.csi.domain.StudentTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository("studentTestDaoImpl")
public class StudentTestDaoImpl implements StudentDao {
@Autowired
private JdbcTemplate jdbcTemplate ;
/* public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}*/
@Override
public int save(Student student) {
String sql = "insert into students (id,name,gender,age,class) values (?,?,?,?,?)" ;
int ret=this.jdbcTemplate.update(sql,student.getId(),student.getName(),student.getGender(),student.getAge(),
student.getClasses());
return ret;
}
@Override
public int modify(Student student) {
String sql="update students set id=?,name=?,gender=?,age=?,class=? where id=?";
int ret=this.jdbcTemplate.update(sql,student.getId(),student.getName(),student.getGender(),student.getAge(),
student.getClasses(),student.getId());
return ret;
}
@Override
public List<Student> list() {
String sql="select id,name,gender,age,class from students";
// new BeanPropertyRowMapper<>(Student.class)
List<Student> list=this.jdbcTemplate.query(sql,(rs,rowNum) -> {
Student student = new Student() ;
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setGender(rs.getString("gender"));
student.setAge(rs.getInt("age"));
student.setClasses(rs.getString("class"));
return student ;
});
return list;
}
@Override
public Student findById(Integer id) {
String sql="select id,name,gender,age,class from students where id=?";
Student stu=this.jdbcTemplate.queryForObject(sql,(rs,rowNum) -> {
Student student = new Student() ;
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setGender(rs.getString("gender"));
student.setAge(rs.getInt("age"));
student.setClasses(rs.getString("class"));
return student ;
},id);
return stu;
}
@Override
public int deleteById(Integer id) {
String sql="delete from students where id=?";
int ret=this.jdbcTemplate.update(sql,id);
return ret;
}
}
package com.csi.service.impl;
import com.csi.dao.StudentDao;
import com.csi.domain.Student;
import com.csi.service.StudentService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("studentTestServiceImpl")
public class StudentTestServiceImpl implements StudentService {
@Resource
private StudentDao studentDao ;
/* public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}*/
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
public int save(Student student) {
return this.studentDao.save(student);
}
@Override
public int modify(Student student) {
return this.studentDao.modify(student);
}
@Override
public List<Student> list() {
return this.studentDao.list();
}
@Override
public Student findById(Integer id) {
return this.studentDao.findById(id);
}
@Override
public int deleteById(Integer id) {
return this.studentDao.deleteById(id);
}
}
package com.csi.controller;
import com.csi.dao.impl.StudentTestDaoImpl;
import com.csi.domain.Student;
import com.csi.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import java.util.List;
@Controller("studentTestController")
public class StudentTestController {
@Autowired
@Qualifier(value = "studentTestServiceImpl")
private StudentService studentService ;
/* public void setStudentService(StudentTestDaoImpl studentService) {
this.studentService = studentService;
}*/
public int save(Student student) {
return this.studentService.save(student);
}
public int modify(Student student) {
return this.studentService.modify(student);
}
public List<Student> list() {
return this.studentService.list();
}
public Student findById(Integer id) {
return this.studentService.findById(id);
}
public int deleteById(Integer id) {
return this.studentService.deleteById(id);
}
}
测试类
import com.csi.controller.StudentController;
import com.csi.controller.StudentTestController;
import com.csi.dao.StudentDao;
import com.csi.domain.BeanTest;
import com.csi.domain.Student;
import com.csi.domain.StudentTest;
import com.csi.service.StudentService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;
public class TestStudentTestController {
@Test
public void save(){
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml") ;
StudentTestController studentTestController = (StudentTestController) ctx.getBean("studentTestController");
Student student=new Student();
student.setId(9);
student.setAge(20);
student.setName("钱十一");
student.setGender("男");
student.setClasses("高中三班");
int save = studentTestController.save(student);
System.out.println(save);
}
@Test
public void list(){
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml") ;
StudentTestController studentTestController = (StudentTestController) ctx.getBean("studentTestController");
List<Student> list = studentTestController.list();
for (Student student : list) {
System.out.println(student);
}
}
@Test
public void findById(){
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml") ;
StudentTestController studentTestController = (StudentTestController) ctx.getBean("studentTestController");
Student byId = studentTestController.findById(1);
System.out.println(byId);
}
@Test
public void update(){
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml") ;
StudentTestController studentTestController = (StudentTestController) ctx.getBean("studentTestController");
Student student=new Student();
student.setId(9);
student.setAge(20);
student.setName("张三");
student.setGender("男");
student.setClasses("高中三班");
int modify = studentTestController.modify(student);
System.out.println(modify);
}
@Test
public void delete(){
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml") ;
StudentTestController studentTestController = (StudentTestController) ctx.getBean("studentTestController");
int i = studentTestController.deleteById(9);
System.out.println(i);
}
}