学习目标:
spring5学习
学习内容:
spring文字讲解:https://zhuanlan.zhihu.com/p/99183015
1、Spring
1.1、简介
spring官网: https://spring.io/projects/spring-framework#overview
官方下载: https://repo.spring.io/release/org/springframework/spring/
GitHub: https://github.com/spring-projects/spring-framework
Spring Web MVC: spring-webmvc最新版
pom.xml中的配置:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
1.2 、优点
Spring是一个开源的免费框架(容器)!
Spring是一个轻量级的非入侵式的框架!
控制反转(IOC),面向切面编程(AOP)!
支持事务的处理,对框架整合的支持。
开源免费容器,轻量级非入侵式,控制反转,mian’xiang
Spring是一个轻量级的控制反转(IOC)和面向切面(AOP)编程的框架。
1.3、组成
1.4扩展
现代化的java开发–>基于Spring的开发
Spring Boot :
一个快速开发的脚手架。
基于SpringBoot可以快速的开发单个微服务。
约定大于配置!
Spring Cloud:
SpringCloud是基于SpringBoot实现的。
因为现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC!承上启下的作用!
弊端:发展太久了之后,违背了原来的理念!配置十分繁琐,人称:“配置地狱!”
2、IOC理论推导
传统的调用
1、UserDao
package dao;
public interface UserDao {
void getUser();
}
2、UserDaoImpl
package dao;
public class UserDaoImpl implements UserDao{
public void getUser() {
System.out.println("默认获取用户数据");
}
}
3、UserSevice
package Service;
public interface UserService {
void getUser();
}
4、UserServiceImp
package Service;
import dao.UserDao;
import dao.UserDaoImpl;
public class UserServiceImpl implements UserService{
UserDao userDao = new UserDaoImpl();
public void getUser(){
userDao.getUser();
}
}
测试:
package holle0;
import Service.UserService;
import Service.UserServiceImpl;
public class MyTest0 {
public static void main(String[] args) {
// 用户实际调用的是业务层,dao层他们不需要接触
UserService userService = new UserServiceImpl();
userService.getUser();
}
}
在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码!如果程序代码量十分大,修改一次的成本代价十分昂贵!
改良:我们使用一个Set接口实现。已经发生了革命性的变化!
UserServiceImpl
//在Service层的实现类(UserServiceImpl)增加一个Set()方法
public class UserServiceImpl implements UserService{
UserDao userDao;
//利用set进行动态实现值的注入!
public void setUserDao(UserDao userDao){
this.userDao=userDao;
}
public void getUser() {
userDao.getUser();
}
}
set()方法实际上是动态改变了UserDao userDao的初始化部分(new UserDaoImpl)。
测试类:
public class myTest {
@Test
public void test(){
//用户实际调用的是业务层,dao层他们不需要接触!
UserServiceImpl userService = new UserServiceImpl();
userService.setUserDao(new UserDaoMysqlImpl());
userService.getUser();
}
}
之前用户想调用哪个UserDao实现类必须事先指定,若之后要改变,需要改变UserServiceImpl代码,加了set方法之后,用户想改变为调哪个UserDao实现类就可以直接new 那个UserDao实现类的对象,不需要改变代码。
之前,程序是主动创建对象!控制权在程序猿手上!
使用了set注入后,程序不再具有主动性,而是变成了被动的接受对象!(主动权在客户手上)。
本质上解决了问题,程序员不用再去管理对象的创建。系统的耦合性大大降低,可以更专注在业务的实现上。这是IOC(控制反转)的原型,反转(理解):主动权交给了用户。
使用 Spring 之后,我们可以将对象的创建、初始化、销毁等操作交给 Spring 容器来管理。就是说,在项目启动时,所有的 Bean 都将自己注册到 Spring 容器中去(如果有必要的话),然后如果其他 Bean 需要使用到这个 Bean ,则不需要自己去 new,而是直接去 Spring 容器去要。
IOC本质:
控制反转IOC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IOC的一种方法,也有人认为DI只是IOC的另一种说法。没有IOC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序的中,对象的创建方式由程序自己控制,控制反转后将对象的创建转移给第三方。
采用XML方式配置Bean的时候,Bean的定义信息和实现是分离的,而采用注解的方式可以把二者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在spring中实现控制反转的是IOC容器,其实现方式是依赖注入DI。
3、HelloSpring
在父模块中导入jar包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
pojo的Hello.java
package pojo;
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return " [str=" + str + "]";
}
}
在resource里面的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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--在Spring中创建对象,在Spring这些都称为bean
类型 变量名 = new 类型();
Holle holle = new Holle();
bean = 对象(holle)
id = 变量名(holle)
class = new的对象(new Holle();)
property 相当于给对象中的属性设值,让str="Spring"
-->
<bean id="hello" class="pojo.Hello">
<property name="str" value="Spring"/>
</bean>
</beans>
测试类MyTest
public class MyTest {
public static void main(String[] args) {
//获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象下能在都在spring·中管理了,我们要使用,直接取出来就可以了
Hello holle = (Hello) context.getBean("hello");
System.out.println(holle.toString());
}
}
核心用set注入,所以必须要有下面的set()方法
//Hello类
public void setStr(String str) {
this.str = str;
}
Hello对象是由Spring创建的,Hello对象的属性是由Spring容器设置的,这个过程就叫控制反转。
控制:传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的。
反转:程序本身不创建对象,而变成被动的接受对象。
依赖注入:就是利用set方法来注入
IOC是一种编程思想,由主动的编程变成被动的接收。
IOC:对象由Spring来创建,管理和装配。
在前面的Service,Dao普通示例中使用Spring
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDaomSql" class="dao.UserDaoMysqlImpl"></bean>
<bean id="userServiceImpl" class="service.UserServiceImp">
<!--ref引用spring中已经创建很好的对象-->
<!--value是一个具体的值,基本数据类型-->
<property name="userDao" ref="userDaomSql"/>
</bean>
</beans>
第一个module改良后测试
public class MyTest0 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("userServiceImpl");
userServiceImpl.getUser();
}
}
说明:所有的类都要装配在beans.xml里面,所有的bean都要通过容器去取,容器里面的bean,拿出来就是一个对象,用对象调用方法即可。用户想调用UserDao的哪个实现类,直接在.xml的ref修改即可。
<bean id="userServiceImpl" class="service.UserServiceImp">
<!--ref引用spring中已经创建很好的对象-->
<!--value是一个具体的值,基本数据类型-->
<property name="userDao" ref="userDaomSql"/>
4、IOC创建对象的方式
1、使用无参构造创建对象,默认。
2、使用有参构造(如下):
下标赋值:
index指的是有参构造中参数的下标,下标从0开始;
<bean id="user" class="pojo.User">
<constructor-arg index="0" value="yyc"/>
</bean>
</beans>
类型赋值
不建议使用,因为可能有参数的类型相同。
<bean id="user" class="pojo.User">
<constructor-arg type="java.lang.String" value="yyc"/>
</bean>
通过参数名
<bean id="user" class="pojo.User">
<constructor-arg name="name" value="yyc"></constructor-arg>
</bean>
<!--比如参数名是name,则有name=“具体值”-->
注册完bean,就实现了对象的初始化(类似new 类名())
注意:参数名方式还需要无参构造和set方法,index和type只需要有参构造。
就算是new两个对象,也是只有一个实例(单例模式:全局唯一)
User user = (User) context.getBean("user");
User user2 = (User) context.getBean("user");
system.out.println(user == user2)//结果为true
总结:在配置文件加载的时候,容器()中管理的对象就已经初始化了.。
5、属性的注入:
在xml配置中。属性的注入存在多种方式。
5.1、构造方法注入:
通过Bean的构造方法给Bean的属性注入值。第四点有提到
第一步:首先给Bean添加对应的构造方法:
public class Book {
private Integer id;
private String name;
private Double price;
public Book() {
System.out.println("-------book init----------");
}
public Book(Integer id, String name, Double price) {
this.id = id;
this.name = name;
this.price = price;
}
}
第二步:在xml文件中注入Bean:
IOC创建对象中提到的两种方法:下标赋值,通过参数名。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean class="org.javaboy.Book" id="book">
<constructor-arg index="0" value="1"/>
<constructor-arg index="1" value="三国演义"/>
<constructor-arg index="2" value="30"/>
</bean>
</beans>
这里需要注意的是,constructor-arg 中的 index 和 Book 中的构造方法参数一一对应。写的顺序可以颠倒,但是 index 的值和 value 要一一对应。
<bean class="org.javaboy.Book" id="book2">
<constructor-arg name="id" value="2"/>
<constructor-arg name="name" value="红楼梦"/>
<constructor-arg name="price" value="40"/>
</bean>
如果有多个构造方法,则会根据给出参数个数以及参数类型,自动匹配到对应的构造方法上,进而初始化一个对象。
5.2、set方法注入
除了构造方法之外,我们也可以通过 set 方法注入值。
依赖注入:set注入!
依赖:bean对象的创建依赖于容器
注入:bean对象中的所有属性,由容器来注入
1、普通值注入:
<bean class="org.javaboy.Book" id="book3">
<property name="id" value="3"/>
<property name="name" value="水浒传"/>
<property name="price" value="30"/>
</bean>
2、复杂属性的注入:对象注入,数组注入,Map注入,Properties注入,null值注入,Set注入。
示例:1、复杂类型:Address类,2、真实测试对象:Student类,3、beans.xml,4、测试:myTest
Student类:
@Get
@Set
public class Student {
//别忘了写get和set方法(用lombok注解也行)
private String name;
private Address address;
private String[] books;
private List<String> hobbies;
private Map<String, String> card;
private Set<String> game;
private Properties infor;
private String wife;
@Override
public String toString() {
return "{" +"\n"+
"name='" + name + '\'' +"\n"+
", address=" + address.toString() +"\n"+
", books=" + Arrays.toString(books) +"\n"+
", hobbies=" + hobbies +"\n"+
", card=" + card +"\n"+
", game=" + game +"\n"+
", infor=" + infor +"\n"+
", wife='" + wife + '\'' +"\n"+
'}';
}
}
Address类:
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "{" +
"address='" + address + '\'' +
'}';
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="address" class="com.yuan.pojo.Address">
<property name="address" value="青岛"/>
</bean>
<bean id="student" class="com.yuan.pojo.Student">
<!--第一种,普通值注入,value-->
<property name="name" value="袁永超"/>
<!--第二种,Bean注入,ref-->
<property name="address" ref="address"/>
<!--第三种,数组注入-->
<property name="books">
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>水浒传</value>
<value>三国演义</value>
</array>
</property>
<!--第四种,list-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>敲代码</value>
<value>看电影</value>
</list>
</property>
<!--第五种,map-->
<property name="card">
<map>
<entry key="身份证" value="15461264461231"/>
<entry key="银行卡" value="14663164464"/>
</map>
</property>
<!--第六种,Set-->
<property name="games">
<set>
<value>LOL</value>
<value>COC</value>
<value>BOB</value>
</set>
</property>
<!--第七种,null-->
<property name="wife">
<null/>
</property>
<!--第八种,Properties-->
<property name="info">
<props>
<prop key="name">yyc</prop>
<prop key="age">22</prop>
</props>
</property>
</bean>
</beans>
myTest测试类:
public class myTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student)context.getBean("student");
System.out.println(student.toString());
}
}
set 方法注入,有一个很重要的问题,就是属性名。很多人会有一种错觉,觉得属性名就是你定义的属性名,这个是不对的。在所有的框架中,凡是涉及到反射注入值的,属性名统统都不是 Bean 中定义的属性名,而是通过 Java 中的内省机制分析出来的属性名,简单说,就是根据 get/set 方法分析出来的属性名。
5.3、拓展注入:
官方文档位置:
pojo新增一个User类用于测试:
public class User {
private String name;
private int id;
public User() {
}
public User(String name, int id) {
super();
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "User [name=" + name + ", id=" + id + "]";
}
}
注意: beans 里面加上这下面两行
使用p和c命名空间需要导入xml约束
xmlns:p=“http://www.springframework.org/schema/p”
xmlns:c=“http://www.springframework.org/schema/c”
p命名空间注入(set注入,需要写无参构造方法)
c命名空间注入(构造器注入,需要写有参构造方法)
<?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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--p命名空间注入(set注入),可以直接注入属性的值:property-->
<bean id="user" class="com.yuan.pojo.User" p:name="yyc" p:age="23"/>
<!--c命名空间注入,通过构造器注入:construct-args-->
<bean id="user2" class="com.yuan.pojo.User" c:age="22" c:name="yyc"/>
</beans>
测试:
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user2", User.class);
System.out.println(user);
}
5.4、外部Bean的注入:
有时候,我们使用一些外部 Bean,这些 Bean 可能没有构造方法,而是通过 Builder 来构造的,这个时候,就无法使用上面的方式来给它注入值了。
此时要用静态工厂注入和示例工厂注入,在笔记开头的链接文章里。
5.5、Bean作用域:
1、单例模式(默认):
单例模式是把对象放在pool中,需要再取出来,使用的都是同一个对象实例。
<bean id="user2" class="pojo.User" c:name="cxk" c:age="19" scope="singleton"></bean>
2、原型模式: 每次从容器中get的时候,都产生一个新对象!
<bean id="user2" class="pojo.User" c:name="cxk" c:age="19" scope="prototype"></bean>
3、其余的request、session、application这些只能在web开发中使用!
6、Spring配置
6.1、别名
<bean id="user" class="pojo.User">
<constructor-arg name="name" value="chen"></constructor-arg>
</bean>
<alias name="user" alias="userLove"/>
<!-- 使用时
User user2 = (User) context.getBean("userLove");
-->
6.2、Bean的配置
<!--
id:bean 的唯一标识符,也就是相当于我们学的对象名
class:bean对象所对应的全限定名:包名+类型
name:也是别名,而且name可以同时取多个别名
可用多种符号分隔,空格,分号,逗号-->
<bean id="userT" class="com.yuan.pojo.UserT" name="user2 u2,u3,u3">
<property name="name" value="yyc"/>
</bean>
<!-- 使用时
User user2 = (User) context.getBean("u2");
-->
6.3、import
import一般用于团队开发使用,它可以将多个配置文件,导入合并为一个
假设,现在项目中有多个人开发,这三个人复制不同的类开发,不同的类需要注册在不同的bean中,我们可以利
用import将所有人的beans.xml合并为一个总的!
张三(beans.xm1)
李四(beans2.xm1)
王五(beans3.xm1)
applicationContext.xml
<import resource="beans.xm1"/>
<import resource="beans2.xml"/>
<import resource="beans3.xm1"/>
使用的时候,直接使用总的配置就可以了。按照在总的xml中的导入顺序来进行创建,后导入的会重写先导入的,最终实例化的对象会是后导入xml中的那个。
7、Bean的自动装配:
自动装配是Spring满足bean依赖的一种方式
Spring会在上下文自动寻找,并自动给bean装配属性
在Spring中有三种装配的方式
1、在xml中显示配置
2、在java中显示配置
3、隐式的自动装配bean【重要】
4、环境搭建:一个人有两个宠物
5、byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid,弊端:名字必须相同。byname的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
6、byType:byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean,弊端:不能有两个相同的类型。bytype的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!
<bean id="people" class="com.yuan.pojo.People" autowire="byName">
<property name="name" value="是甪黎呀"/>
<!-- <property name="dog" ref="dog"/>-->
<!-- <property name="cat" ref="cat"/>-->
</bean>
7.1、测试:自动装配
pojo的Cat类
public class Cat {
public void shut(){
System.out.println("miao");
}
}
pojo的Dog类
public class Dog {
public void shut(){
System.out.println("wow");
}
}
pojo的People类
package pojo;
public class People {
private Cat cat;
private Dog dog;
private String name;
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "{" +
"cat=" + cat +
", dog=" + dog +
", name='" + name + '\'' +
'}';
}
}
xml配置–>byType自动装配
<bean id="cat" class="com.yuan.pojo.Cat"/>
<bean id="dog" class="com.yuan.pojo.Dog"/>
<!--byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean,弊端:不能有两个相同的类型
例如Dog dog 那么就会查找pojo的Dog类,再进行自动装配-->
<bean id="people" class="com.yuan.pojo.People" autowire="byType">
<property name="name" value="是甪黎呀"/>
<!--以下两句手动装配就不需要写了-->
<!-- <property name="dog" ref="dog"/>-->
<!-- <property name="cat" ref="cat"/>-->
</bean>
</beans>
xml配置–>byName自动装配
<bean id="cat" class="pojo.Cat"/>
<bean id="dog" class="pojo.Dog"/>
<!--byname会在容器自动查找,和自己对象set方法的set后面的值对应的id
例如:setDog(),取set后面的字符作为id,则要id = dog 才可以进行自动装配
byname的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
-->
<bean id="people" class="pojo.People" autowire="byName">
<property name="name" value="cbh"></property>
</bean>
注意:byName只能取到小写,大写取不到。
7.2、使用注解实现自动装配
jdk1.5支持的注解,spring2.5支持的注解
The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.(翻译:基于注释的配置的引入提出了一个问题,即这种方法是否比XML“更好”)
1、导入contest约束
xmlns:context=“http://www.springframework.org/schema/context”
2、配置注解的支持:context:annotan-config/
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启注解的支持-->
<context:annotation-config/>
</beans>
7.2.1、@Autowired
默认是byType方式,如果匹配不上,就会用byName方式
可以在属性上使用,也可以在set方法上使用
此时可以不用为属性写set方法了,前提是这个自动装配的属性在IOC(Spring)容器中存在,且要符合ByName自动装配。
public class People {
@Autowired
private Cat cat;
@Autowired
private Dog dog;
private String name;
}
@Nullable :字段标记了这个注解的话,说明这个字段可以为null
public name(@Nullable String name){
}
//源码
public interface @Autowired {
boolean required() default true;
}
如果定义了Autowire的require属性为false,说明这个对象可以为null,否则不允许为空(false表示找不到装配,不抛出异常)。
7.2.2、@Autowired+@Qualifier
@Autowired不能唯一装配时,需要@Autowired+@Qualifier
如果@Autowired自动装配环境比较复杂。自动装配无法通过一个注解完成的时候,可以使用@Qualifier(value = “dog”)去配合使用,指定一个唯一的id对象。
public class People {
@Autowired
private Cat cat;
@Autowired
@Qualifier(value = "dog")
private Dog dog;
private String name;
}
如果xml文件中同一个对象被多个bean使用,Autowired无法按类型找到,可以用@Qualifier指定id查找。
7.2.3、@Resource
默认是byName方式,如果匹配不上,就会byType。
public class People {
@Resource(name="cat")
private Cat cat;
@Resource(name="dog")
private Dog dog;
private String name;
}
@Resource和@Autowired的区别:
都是用来自动装配的,都可以放在属性字段上
@Autowired通过byType的方式实现,而且必须要求这个对象存在!【常用】
@Resource默认通过byname的方式实现,如果找不到名字,则通过byType实现,如果两个都找不到的情况下,就报错【常用】
执行的顺序不同:@Autowired通过byType的方式实现。 @Resource默认通过byname的方式实现。
8、使用注解开发
在spring4之后,使用注解开发,必须要保证aop包的导入。
使用注解需要导入contex的约束。
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
8.1、bean
有了< context:component-scan>,另一个< context:annotation-config/>标签可以移除掉,因为已经被包含进去了。
<!--指定要扫描的包,这个包下面的注解才会生效
别只扫一个com.yuan.pojo包-->
<context:component-scan base-package="com.yuan"/>
<context:annotation-config/>
//@Component 组件
//等价于<bean id="user" classs"pojo.User"/>
@Component
public class User {
public String name ="袁永超";
}
8.2、属性如何注入@value
@Component
public class User {
//相当于<property name="name" value="kuangshen"/>
@value("kuangshen")
public String name;
//也可以放在set方法上面
//@value("kuangshen")
public void setName(String name) {
this.name = name;
}
}
8.3、衍生的注解
@Component有几个衍生注解,会按照web开发中,mvc架构中分层。
- dao (@Repository)
- service(@Service)
- controller(@Controller)
这四个注解的功能是一样的,都是代表将某个类注册到容器中。
8.4、自动装配置
@Autowired:默认是byType方式,如果匹配不上,就会byName
@Nullable:字段标记了这个注解,说明该字段可以为空
@Resource:默认是byName方式,如果匹配不上,就会byType
8.5、作用域@scope
//原型模式prototype,单例模式singleton
//@scope("prototype")相当于<bean scope="prototype"></bean>
@Component
@scope("prototype")
public class User {
//相当于<property name="name" value="yyc"/>
@value("yyc")
public String name;
//也可以放在set方法上面
@value("yyc")
public void setName(String name) {
this.name = name;
}
}
8.6、小结
xml与注解:
- xml更加万能,维护简单,适用于任何场合
- 注解,不是自己的类使用不了,维护复杂
最佳实践:
- xml用来管理bean
- 注解只用来完成属性的注入
- 要开启注解支持
9、使用Java的方式配置Spring
不使用Spring的xml配置,完全交给java来做!
Spring的一个子项目,在spring4之后,它成为了核心功能
实体类:pojo的User.java
//这里这个注解的意思,就是说明这个类被Spring接管了,注册到了容器中
@component
public class User {
private String name;
public String getName() {
return name;
}
//属性注入值
@value("yyc')
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "user{" +
"name='" + name + '\''+
'}';
}
}
弹幕评论:要么使用@Bean,要么使用@Component和ComponentScan,两种效果一样。自己做的是去掉@Bean后报错NoSuchBeanDefinitionException: No bean named ‘getUser’ available。
配置文件:config中的myConfig.java
@Import(myConfig2.class),用@import来包含myConfig2.java
//这个也会Spring容器托管,注册到容器中,因为他本米就是一个@Component
// @Configuration表这是一个配置类,就像我们之前看的beans.xml,类似于<beans>标签
@Configuration
@componentScan("com.yuan.pojo") //开启扫描
//@Import(myConfig2.class)
public class myConfig {
//注册一个bean , 就相当于我们之前写的一个bean 标签
//这个方法的名字,就相当于bean 标签中的 id 属性 ->getUser
//这个方法的返同值,就相当于bean 标签中的class 属性 ->User
@Bean
public User getUser(){
return new User(); //就是返回要注入到bean的对象!
}
}
弹幕评论:ComponentScan、@Component("pojo”) 这两个注解配合使用
测试类
public class MyTest {
public static void main(String[ ] args) {
//如果完全使用了配置类方式去做,我们就只能通过 Annotationconfig 上下文来获取容器,通过配置类的class对象加载!
ApplicationContext context = new AnnotationConfigApplicationContext(myConfig.Class); //class对象
User getUser =(User)context.getBean( "getUser"); //方法名getUser
System.out.Println(getUser.getName());
}
}
会创建两个相同对象问题的说明(自己没有遇到):
弹幕总结 - -> @Bean是相当于< bean>标签创建的对象,而我们之前学的@Component是通过spring自动创建的这个被注解声明的对象,所以这里相当于有两个User对象被创建了。一个是bean标签创建的(@Bean),一个是通过扫描然后使用@Component,spring自动创建的User对象,所以这里去掉@Bean这些东西,然后开启扫描。之后在User头上用@Component即可达到spring自动创建User对象了。
10、动态代理
代理模式是SpringAOP的底层
分类:动态代理和静态代理
10.1、静态代理
代码示例:
1、接口(租房)
package pojo;
public interface Rent {
public void rent();
}
2、真实角色(房东)
package pojo;
public class Host implements Rent{
public void rent() {
System.out.println("房东要出租房子");
}
}
3、代理角色(中介)
package com.yuan.demo01;
public class Proxy implements Rent{
private Host host;
public Proxy(){
}
public Proxy(Host host) {
this.host = host;
}
public void rent() {
seeHouse();
host.rent();
hetong();
fee();
}
//看房
public void seeHouse(){
System.out.println("中介带你看房");
}
//收中介费
public void fee(){
System.out.println("收中介费");
}
//合同
public void hetong(){
System.out.println("签租赁合同");
}
}
4、客户端访问代理角色(客户找中介)
package com.yuan.demo01;
public class Client {
public static void main(String[] args) {
//房东要租房子
Host host = new Host();
//代理,中介帮房东租房子,但是代理一般会有一些附属操作!
Proxy proxy = new Proxy(host);
//看不到房东,但通过代理,还是租到了房子
proxy.rent();
}
}
代码翻倍:几十个真实角色就得写几十个代理。
AOP横向开发
10.2、动态代理
动态代理和静态角色一样,动态代理底层是反射机制
动态代理类是动态生成的,不是我们直接写好的!
动态代理(两大类):基于接口,基于类
- 基于接口:JDK的动态代理【使用ing】
- 基于类:cglib
- java字节码实现:javasisit
了解两个类
1、Proxy:代理类
2、InvocationHandler:调用处理程序
实例:
接口Rent.java
/租房
public interface Rent {
public void rent();
}
接口Rent实现类 Host.java
public class Host implements Rent{
public void rent() {
System.out.println("房东要出租房子!");
}
}
代理角色的处理程序类 ProxyInvocationHandler.java
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
}
//处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//动态代理的本质,就是使用反射机制实现!
seeHouse();
Object result = method.invoke(rent, args);
return result;
}
public void seeHouse(){
System.out.println("中介带看房子");
}
}
用户类 Client.java
public class Client {
public static void main(String[] args) {
//真实角色
Host host=new Host();
//代理角色,需要生成
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//通过调用程序处理角色来处理我们要调用的接口对象
pih.setRent(host);
Rent proxy = (Rent)pih.getProxy();
proxy.rent();
}
}
改成万能代理类:
///用这个类,自动生代理
public class ProxyInvocationHandler implements InvocationHandler {
// 被代理的接口
public Object target;
public void setTarget(Object target) {
this.target = target;
}
// 得到生成的代理类 -> 固定的代码
public Object getProxy() {
return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
// 处理代理实例并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 动态代理的本质,就是使用反射机制实现的
// invoke()执行它真正要执行的方法
Object result = method.invoke(target, args);
return result;
}
}
用户类Client:
public class Client {
public static void main(String[] args) {
//真实角色
UserServiceImpl userService=new UserServiceImpl();
//代理角色,需要生成
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTaeget(userService); //设置要代理的对象
//动态生成代理类
UserService proxy = (UserService)pih.getProxy();
proxy.add();
}
}
11、AOP
11.1 什么是AOP
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重点内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
11.2、AOP在Spring中的使用
提供声明式事务,允许用户自定义切面。
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等…
- 切面(Aspect):横切关注点 被模块化的特殊对象。即,它是一个类。(Log类)
- 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。(Log类中的方法)
- 目标(Target):被通知对象。(生成的代理类) 代理(Proxy):向目标对象应用通知之后创建的对象。(生成的代理类)
- 切入点(PointCut):切面通知执行的”地点”的定义。(最后两点:在哪个地方执行,比如:method.invoke())
- 连接点(JointPoint):与切入点匹配的执行点。
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
11.3、使用Spring实现AOP
导入jar包`
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
11.3.1、方法一:使用原生spring接口
springAPI接口实现
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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
<bean id="UserService" class="com.yuan.service.UserServiceImpl"/>
<bean id="log" class="com.yuan.log.Log"/>
<bean id="afterLog" class="com.yuan.log.AfterLog"/>
<!--方式一:使用原生Spring API接口-->
<!--配置aop:需要导入aop的约束-->
<aop:config>
<!--切入点:expression:表达式,execution(要执行的位置! *****)-->
<aop:pointcut id="pointcut" expression="execution(* com.yuan.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加!-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
execution(返回类型,类名,方法名(参数)) -> execution(* com.service.,(…))
UserService.java
package com.yuan.service;
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
UserService 的实现类 UserServiceImpl.java
package com.yuan.service;
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("增加了一个用户");
}
public void delete() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("修改了一个用户");
}
public void select() {
System.out.println("查询了一个用户");
}
}
前置Log.java
package com.yuan.log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
//method:要执行的目标对象的方法
//args:参数
//target:目标对象
public class Log implements MethodBeforeAdvice {
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass()+"的"+method.getName()+"被执行了");
}
}
后置AfterLog.java
package com.yuan.log;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class AfterLog implements AfterReturningAdvice {
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回结果为:"+returnValue);
}
}
测试类
import com.yuan.service.UserService;
import com.yuan.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class myTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理代理的是接口
UserService userService = (UserService)context.getBean("UserService");
userService.add();
}
}
11.3.2、方法二:自定义类实现AOP
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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
<bean id="userservice" class="service.UserServiceImpl"/>
<bean id="log" class="log.Log"/>
<bean id="afterLog" class="log.AfterLog"/>
<!-- 方式二,自定义 -->
<bean id="diy" class="diy.DiyPointcut"/>
<aop:config>
<!--自定义切面-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* service.UserServiceImpl.*(..))"/>
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
</beans>
diy类:
package com.yuan.diy;
public class DiyPointCut {
public void before(){
System.out.println("===========方法执行前==========");
}
public void after(){
System.out.println("===========方法执行后==========");
}
}
测试类:
//测试
public class myTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//注意:动态代理代理的是接口
UserService userService = (UserService) context.getBean("userservice");
userService.add();
}
}
11.3.3、方法三:使用注解实现
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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 注册 -->
<bean id="userservice" class="service.UserServiceImpl"/>
<!--方式三,使用注解实现-->
<bean id="diyAnnotation" class="diy.DiyAnnotation"></bean>
<!-- 开启自动代理
实现方式:默认JDK (proxy-targer-class="fasle")
cgbin (proxy-targer-class="true")-->
<aop:aspectj-autoproxy/>
</beans>
DiyAnnotation.java
package com.yuan.diy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
//方式三:使用注解方式实现AOP
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {
@Before("execution(* com.yuan.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("===========方法执行前==========");
}
@After("execution(* com.yuan.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("===========方法执行后===========");
}
//在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点:
@Around("execution(* com.yuan.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable{
System.out.println("环绕前");
Object proceed = jp.proceed(); //执行方法
System.out.println("环绕后");
Signature signature = jp.getSignature();//获得签名
System.out.println("signature"+signature);
System.out.println(proceed);
}
}
测试类:
public class myTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//注意:动态代理代理的是接口
UserService userService = (UserService) context.getBean("userservice");
userService.add();
}
}
12、整合mybatis
mybatis-spring官网:https://mybatis.org/spring/zh/
回顾mybatis的配置流程:
-
编写实体类
-
编写核心配置文件
-
编写接口
-
编写Mapper.xml
-
测试
12.1、mybatis-spring-方式一 -
编写数据源配置
-
sqISessionFactory
-
sqISessionTemplate(相当于sqISession)
-
需要给接口加实现类【new】
-
将自己写的实现类,注入到Spring中
-
测试!
导入jar包:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--Spring操作数据库的话,还需要一个spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
</dependencies>
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
编写顺序:
User -> UserMapper -> UserMapper.xml -> spring-dao.xml -> UserServiceImpl -> applicationContext.xml -> myTest
代码示例:
pojo实体类 User
package com.yuan.pojo;
import lombok.Data;
@Data
public class User {
private int id;
private String name;
private String password;
}
mapper目录下的 UserMapper、UserMapperImpl、UserMapperImpl2、UserMapper.xml
接口UserMapper
package com.yuan.mapper;
import com.yuan.pojo.User;
import java.util.List;
public interface UserMapper {
public List<User> selectUser();
}
UserMapperImpl
package com.yuan.mapper;
import com.yuan.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserMapperImpl implements UserMapper{
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuraton核心配置文件-->
<mapper namespace="com.yuan.mapper.UserMapper">
<select id="selectUser" resultType="user">
select * from user;
</select>
</mapper>
resource目录下的 mybatis-config.xml、spring-dao.xml、applicationContext.xml
mybatis-config.xml 只留下了配置和别名,剩余的放在了spring-dao.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">
<!--configuraton核心配置文件-->
<configuration>
<!--给实体类起别名-->
<typeAliases>
<package name="com.yuan.pojo"/>
</typeAliases>
<!--设置-->
<!--<settings>
<setting name="" value=""/>
</settings>-->
</configuration>
spring-dao.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid-->
<!--我们这里使用Spring提供的JDBC-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="yyc"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<!--绑定Mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/yuan/mapper/*.xml"/>
</bean>
<!--SqlSessionTemplate:就是我们使用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="spring-dao.xml"/>
<bean id="userMapper" class="com.yuan.mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
<bean id="userMapper2" class="com.yuan.mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
测试类
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import mapper.UserMapper;
import pojo.User;
public class myTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = (UserMapper) context.getBean("userMapper");
for (User user : userMapper.getUser()) {
System.out.println(user);
}
}
}
12.2、mybatis-spring-方式二
UserServiceImpl2
package com.yuan.mapper;
import com.yuan.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
public List<User> selectUser() {
SqlSession sqlSession = getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
//return getSqlSession().getMapper(UserMapper.class).selectUser();
}
}
测试:
public class myTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = (UserMapper) context.getBean("userMapper2");
for (User user : userMapper.getUser()) {
System.out.println(user);
}
}
}
13. 声明式事务
- 把一组业务当成一个业务来做;要么都成功,要么都失败!
- 事务在项目开发中,十分的重要,涉及到数据的一致性问题
- 确保完整性和一致性
事务的ACID原则:
1、原子性
2、隔离性
3、一致性
4、持久性
Spring中的事务管理- 声明式事务:AOP
- 编程式事务:需要在代码中,进行事务管理
声明式事务
先在pom.xml文件导入jar包
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
</dependencies>
<!--在build中配置resources,来防止资源导出失败的问题-->
<!-- Maven解决静态资源过滤问题 -->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
代码示例:
pojo实体类 User
package com.yuan.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String password;
}
mapper目录下的 UserMapper、UserMapperImpl、UserMapper.xml
接口UserMapper
package com.yuan.mapper;
import com.yuan.pojo.User;
import java.util.List;
public interface UserMapper {
public List<User> selectUser();
//添加一个用户
public int addUser(User user);
//删除一个用户
public int deleteUser(int id);
}
}
UserMapperImpl
package com.yuan.mapper;
import com.yuan.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
public List<User> selectUser() {
User user = new User(5, "小高", "567");
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
mapper.addUser(user);
mapper.deleteUser(4);
return mapper.selectUser();
}
public int addUser(User user) {
return getSqlSession().getMapper(UserMapper.class).addUser(user);
}
public int deleteUser(int id) {
return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
}
}
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuraton核心配置文件-->
<mapper namespace="com.yuan.mapper.UserMapper">
<select id="selectUser" resultType="user">
select * from user;
</select>
<insert id="addUser" parameterType="user">
insert into user(id, name, password) values(#{id},#{name},#{password});
</insert>
<delete id="deleteUser" parameterType="int">
delete from user where id=#{id}
</delete>
</mapper>
resource目录下的 mybatis-config.xml、spring-dao.xml、applicationContext.xml
mybatis-config.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">
<!--configuraton核心配置文件-->
<configuration>
<!--给实体类起别名-->
<typeAliases>
<package name="com.yuan.pojo"/>
</typeAliases>
</configuration>
spring-dao.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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid-->
<!--我们这里使用Spring提供的JDBC-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="yyc"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<!--绑定Mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/yuan/mapper/*.xml"/>
</bean>
<!--SqlSessionTemplate:就是我们使用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"/>
</bean>
<!--结合AOP实现事务的织入
配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给哪些方法配置事务-->
<!--配置事务的传播特性:new东西 propagation-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="select" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.yuan.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
</beans>
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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="spring-dao.xml"/>
<!--bean-->
<bean id="userMapper" class="com.yuan.mapper.UserMapperImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
测试类:
import com.yuan.mapper.UserMapper;
import com.yuan.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class myTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}
}
事务的重要性:
-
如果不配置事务,可能存在数据提交不一致的情况下;
-
如果不在spring中去配置声明式事务,我们就需要在代码中手动配置事务!
-
事务在项目的开发中非常重要,涉及到数据的一致性和完整性问题!