Spring5(下)

引言

紧接上次,Spring5(上)后,继续学习了Spring5,并进行了整理。

7、Bean自动装配

  • 自动装配是Spring满足bean依赖一种方式!
  • Spring会在上下文中自动寻找,并自动给bean装配属性!

在Spring中有三种装配的方式

​ 1.在xml中显示的配置

​ 2.在java中显示配置

​ 3.隐式的自动装配bean【重要】

7.1 测试

环境搭建:创建项目,一个人有两个宠物!

<bean id="cat" class="com.kuang.pojo.Cat"/>
<bean id="dog" class="com.kuang.pojo.Dog"/>

<bean id="people" class="com.kuang.pojo.People">
    <property name="name" value="小白莲"/>
    <property name="cat" ref="cat"/>
    <property name="dog" ref="dog"/>
</bean>

7.2 ByName自动装配

    <!--
    byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的bean id!
        -->
    <bean id="people" class="com.kuang.pojo.People" autowire="byName">
        <property name="name" value="小白莲"/>
    </bean>

7.3 ByType自动装配

    <!--
    byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean!
        -->
    <bean id="people" class="com.kuang.pojo.People" autowire="byType">
        <property name="name" value="小白莲"/>
    </bean>

小结:

  • ByName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
  • ByType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!

7.4 使用注解实现自动装配

jdk1.5支持的注解,Spring2.5就支持注解了!

要使用注解须知:

​ 1.导入约束:context约束
2.配置注解的支持 context:annotation-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"
       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>

@Autowired

直接在属性上使用即可!也可以在set方法上使用!

使用Autowired我们就可以不用编写set方法了,前提是你这个自动配置的属性在IOC(Spring)容器中存在,且符合名字ByName!

科普:

@Nullable 字段标记了了这个注解,说明这个字段可以为null;

public @interface Autowired {
    boolean required() default true;
}

测试代码

public class People {
    //如果显式定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;
}

如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value = “xxx”)去配置@Autowired的使用,指定一个唯一的bean对象注入!

public class People {
    @Autowired
    @Qualifier(value = "cat111")
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog222")
    private Dog dog;
    private String name;
}

@Resource

public class People {

    @Resource
    private Cat cat;

    @Resource
    private Dog dog;
}

小结:

@Resource和@Autowired的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • @Autowired通过byType的方式实现,而且必须要求这个对象存在!【常用】
  • @Resource默认通过byName的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就报错!【常用】
  • 执行顺序不同:@Autowired通过byType的方式实现。

8、使用注解开发

在Spring4之后,要使用注解开发,必须要保证aop的包导入了

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WyGAdjzi-1645181747534)(C:\Users\54546\AppData\Roaming\Typora\typora-user-images\image-20220121161255758.png)]

使用注解需要导入约束,配置注解的支持!

	<?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>

1.bean

2.属性如何注入

//等价于<bean id="user" class="com.ahao.pojo.User"/>
//@Component 组件

@Component
public class User {

    //相当于  <property name="name" value="白莲"/>
    @Value("白莲")
    public String name;
}

3.衍生的注解

@Component有几个衍生注解,我们在web开发中,会按照mvc三层架构分层!

dao 【@Repository】
service 【@Service】
controller 【@Controller

这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean

4.自动装配

- @Autowired:自动装配通过类型,名字。如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value = "xxx")去配置。
- @Nullable 字段标记了了这个注解,说明这个字段可以为null;
- @Resource:自动装配通过名字,类型。

5.作用域@Scope(“singleton”)

@Component
@Scope("singleton")
public class User {

    //相当于  <property name="name" value="白莲"/>
    @Value("白莲")
    public String name;
}

6.小结
xml与注解:
xml更加万能,适用于任何场合!维护简单方便
注解不是自己类使用不了,维护相队复杂!
xml与注解最佳实践:
xml用来管理bean;
注解只负责完成属性的注入;
我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持

    <!--指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.kuang"/>
    <!--开启注解的支持    -->
    <context:annotation-config/>

9、使用Java的方式配置Spring

我们现在要完全不使用Spring的xml配置了,全权交给Java来做!
JavaConfig是Spring的一个子项目,在Spring4之后,它成为了一个核心功能!

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OX6gqoB0-1645181747537)(C:\Users\54546\AppData\Roaming\Typora\typora-user-images\image-20220121193336089.png)]

实体类

package com.ahao.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;

@Controller
public class User {
    private String name;

    public String getName() {
        return name;
    }

    @Value("ahao")
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

配置文件

package com.ahao.config;

import com.ahao.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

// 这个也会Spring容器托管,注册到容器中,因为他本来就是一个@Component
// @Configuration代表这是一个配置类,就和我们之前看的beans.xml一样
@Configuration
@ComponentScan("com.ahao.pojo")
@Import(MyConfig2.class)
public class MyConfig {

    //注册一个bean,就相当于我们之前写的一个bean标签
    //这个方法的名字,就相当于bean标签中的id属性
    //这个方法的返回值,就相当于bean标签中的class属性
    @Bean
    public User getUser(){
        return new User(); //就是返回要注入到bean的对象!
    }

}

测试类

import com.ahao.config.MyConfig;
import com.ahao.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载!
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User getUser = (User) context.getBean("getUser");
        System.out.println(getUser.getName());
    }
}

这种纯Java的配置方式,在SpringBoot中随处可见!

10、代理模式

为什么要学习代理模式?因为这就是SpringAOP的底层!【SpringAOP和SpringMVC】

代理模式的分类:

  • 静态代理
  • 动态代理

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CnFVepWp-1645181747538)(C:\Users\54546\AppData\Roaming\Typora\typora-user-images\image-20220121201043892.png)]

10.1、静态代理

角色分析:

  • 抽象角色:一般会使用接口或者抽象类解决
  • 真实角色:被代理的角色
  • 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作
  • 客户:访问代理对象的人!

代码步骤:

  1. 接口
//租房
public interface Rent {
    public void rent();
}

2.真实角色

//房东
public class Host implements Rent{
    public void rent() {
        System.out.println("房东出租房子!");
    }
}

3.代理角色

public class Proxy implements Rent{
    private Host host;

    public Proxy() {
    }

    public Proxy(Host host) {
        this.host = host;
    }

    public void rent() {
        host.rent();
        seeHouse();
        sign();
        fee();
    }

    //看房
    public void seeHouse(){
        System.out.println("中介带着看房子!");
    }

    //签合同
    public void sign(){
        System.out.println("和中介签署租赁合同!");
    }

    //收费用
    public void fee(){
        System.out.println("中介收取费用!");
    }
}

4.客户端访问代理角色

public class Client {
    public static void main(String[] args) {
        //房东要出租房子
        Host host = new Host();
//        host.rent();

        //代理,中介帮房东出租房子,并且代理角色一般会有一些附属操作!
        Proxy proxy = new Proxy(host);

        //不用面对房东,直接找中介租房即可!
        proxy.rent();
    }
}

代理模式的好处:

  • 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
  • 公共角色就交给代理角色!实现了业务的分工!
  • 公共业务发生扩展的时候,方便集中管理!

缺点:

  • 一个真实角色就会产生一个代理角色,代码量会翻倍,开发效率会变低~

10.2、加深理解

代码步骤:

  1. 接口
public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void query();
}

2.真实角色

//真实角色
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 query() {
        System.out.println("查询了一个用户!");
    }
}

3.代理角色

public class UserServiceProxy implements UserService{
    private UserServiceImpl userService;

    public void setUserService(UserServiceImpl userService) {
        this.userService = userService;
    }

    public void add() {
        log("add");
        userService.add();
    }

    public void delete() {
        log("delete");
        userService.delete();
    }

    public void update() {
        log("update");
        userService.update();
    }

    public void query() {
        log("query");
        userService.query();
    }

    public void log(String msg){
        System.out.println("[Debug] 使用了一个"+msg+"方法");
    }
}

4.客户端访问代理角色

public class Client {
    public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();

        UserServiceProxy proxy = new UserServiceProxy();
        proxy.setUserService(userService);

        proxy.delete();
    }
}

代理模式的好处:

  • 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
  • 公共角色就交给代理角色!实现了业务的分工!
  • 公共业务发生扩展的时候,方便集中管理!

缺点:

  • 一个真实角色就会产生一个代理角色,代码量会翻倍,开发效率会变低~

聊聊AOP

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QxxS2jOc-1645181747540)(C:\Users\54546\AppData\Roaming\Typora\typora-user-images\image-20220121214945770.png)]

10.3 动态代理

  • 动态代理和静态代理角色一样
  • 动态代理的代理类是动态生成的,不是我们直接写好的!
  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
    • 基于接口 — JDK动态代理【我们在这里使用】
    • 基于类:cglib
    • java字节码实现:javassist

需要了解两个类:Proxy:代理;InvocationHandler:调用处理程序。

代码步骤:

1.接口

public interface Rent {
    public void rent();
}

2.真实角色

public class Host implements Rent{
    public void rent() {
        System.out.println("房东要出租房子!");
    }
}

3.ProxyInvocationHandler类

//我们会用这个类,自动生成代理类!
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 {
        //动态代理的本质,就是使用反射机制实现!
        Object result = method.invoke(rent, args);
        seeHose();
        fee();
        return result;
    }

    public void seeHose(){
        System.out.println("中介带着看房子!");
    }

    public void fee(){
        System.out.println("中介收取费用!");
    }
}

4.测试

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就是动态生成的,我们并没有写
        proxy.rent();

    }
}

在此,我们可以提炼出ProxyInvocationHandler作为工具类

//用这个类自动生成代理类!
public class ProxyInvocationHandler implements InvocationHandler {

    //被代理的接口
    private 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 {
        log(method.getName());
        Object result = method.invoke(target, args);
        return result;
    }

    public void log(String msg){
        System.out.println("[Debug] 使用了一个"+msg+"方法");
    }
}

动态代理的好处:

  • 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
  • 公共角色就交给代理角色!实现了业务的分工!
  • 公共业务发生扩展的时候,方便集中管理!
  • 一个动态代理类代理的是一个接口,一般就是对应的一类业务
  • 一个动态代理类可以代理多个类,只要是实现了同一个接口即可!

11、AOP

11.1 什么是AOP

AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YlOg8pz8-1645181747542)(C:\Users\54546\AppData\Roaming\Typora\typora-user-images\image-20220122150105179.png)]

11.2 AOP在Spring中的作用

提供声明式事务;允许用户自定义切面

  • 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等…
  • 切面(ASPECT):横切关注点被模块化的特殊对象。即,它是一个类。
  • 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
  • 目标(Target):被通知对象。
  • 代理(Proxy):向目标对象应用通知之后创建的对象。
  • 切入点(PointCut):切面通知执行的“地点”的定义。
  • 连接点(JointPoint):与切入点匹配的执行点。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1irRKTIs-1645181747542)(C:\Users\54546\AppData\Roaming\Typora\typora-user-images\image-20220122150544181.png)]

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qZ2lK8zE-1645181747543)(C:\Users\54546\AppData\Roaming\Typora\typora-user-images\image-20220122150610480.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZKRkUdSJ-1645181747543)(C:\Users\54546\AppData\Roaming\Typora\typora-user-images\image-20220122150925867.png)]

即AOP在不改变原有代码的情况下,去增加新的功能。

11.3使用Spring实现AOP

【重点】使用AOP织入,需要导入一个依赖包!

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>

方式一: 使用Spring的API接口【主要是SpringAPI接口实现】

1.在service包下,定义UserService业务接口和UserServiceImpl实现类

public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void select();
}
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("查询了一个用户!");
    }
}

2.在log包下,定义我们的增强类,一个Log前置增强和一个AfterLog后置增强类

public class Log implements MethodBeforeAdvice {

    //method: 要执行的目标对象的方法
    //args:参数
    //target:目标对象
    public void before(Method method, Object[] agrs, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}
public class AfterLog implements AfterReturningAdvice {
    //returnValue: 返回值
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法,返回结果为:"+returnValue);
    }
}

3.最后去spring的文件中注册 , 并实现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="com.kuang.service.UserServiceImpl"/>
    <bean id="log" class="com.kuang.log.Log"/>
    <bean id="afterLog" class="com.kuang.log.AfterLog"/>

    <!--方式一:使用原生Spring API接口-->
    <!--配置aop:需要导入aop的约束-->
    <aop:config>
        <!--切入点:expression:表达式,execution(要执行的位置!* * * * *)-->
        <aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>

        <!--执行环绕增加!-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>

</beans>

4.测试

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        //动态代理代理的是接口:注意点
        UserService userService = (UserService) context.getBean("userService");

        userService.add();
//        userService.select();
    }
}

方式二: 自定义类来实现AOP【主要是切面定义】

1.在diy包下定义自己的DiyPointCut切入类

public class DiyPointCut {
    public void before(){
        System.out.println("======方法执行前======");
    }

    public void after(){
        System.out.println("======方法执行后======");
    }
}

2.去spring中配置文件

    <!--方式二:自定义类-->
    <bean id="diy" class="com.kuang.diy.DiyPointCut"/>

    <aop:config>
        <!--自定义切面,ref 要引用的类-->
        <aop:aspect ref="diy">
            <!--切入点-->
            <aop:pointcut id="point" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
            <!--通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

3.测试

方式三: 使用注解实现!

1.在diy包下定义注解实现的AnnotationPointCut增强类

//声明式事务!
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {

    @Before("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("====方法执行前====");
    }

    @After("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("====方法执行后====");
    }

    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点;
    @Around("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable{
        System.out.println("环绕前");

        Signature signature = jp.getSignature();// 获得签名
        System.out.println("signature:"+signature);

        Object proceed = jp.proceed(); //执行方法

        System.out.println("环绕后");

        System.out.println(proceed);
    }

}

2.在Spring配置文件中,注册bean,并增加支持注解的配置。

    <!--方式三:使用注解-->
    <bean id="annotationPointCut" class="com.kuang.diy.AnnotationPointCut"/>
    <!--开启注解支持! JDK(默认是 proxy-target-class="false")  cglib(proxy-target-class="true")-->
    <aop:aspectj-autoproxy/>

3.测试

后续的等待学完Mysql再回来

12、整合Mybatis

步骤:

  1. 导入相关jar包

    • junit

      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.12</version>
      </dependency>
      
    • mybatis

      <!--mybatis-->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.5.4</version>
      </dependency>
      
    • mysql数据库:mysql-connector-java

      <!--mysqlq驱动-->
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>8.0.22</version>
      </dependency>
      
    • spring相关的:spring-webmvc

      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-webmvc</artifactId>
         <version>5.1.10.RELEASE</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-jdbc</artifactId>
         <version>5.1.10.RELEASE</version>
      </dependency>
      
    • aspectJ AOP 织入器

      <dependency>
         <groupId>org.aspectj</groupId>
         <artifactId>aspectjweaver</artifactId>
         <version>1.9.4</version>
      </dependency>
      
    • mybatis-spring整合包【重点】

      <dependency>
         <groupId>org.mybatis</groupId>
         <artifactId>mybatis-spring</artifactId>
         <version>2.0.2</version>
      </dependecy>
      
    • 配置Maven静态资源过滤问题!【约定大于配置】

      <build>
          <resources>
              <resource>
                  <directory>src/main/resources</directory>
                  <includes>
                      <include>**/*.properties</include>
                      <include>**/*.xml</include>
                  </includes>
                  <filtering>true</filtering>
              </resource>
              <resource>
                  <directory>src/main/java</directory>
                  <includes>
                      <include>**/*.properties</include>
                      <include>**/*.xml</include>
                  </includes>
                  <filtering>true</filtering>
              </resource>
          </resources>
      </build>
      
  2. 编写配置文件

  3. 测试

12.1、回忆mybatis

  1. 编写实体类

    import lombok.Data;
    
    @Data
    public class User {
        public int id;
        public String name;
        public String pwd;
    }
    
  2. 编写核心配置文件

    <?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>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=ture&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=Asia/Shanghai"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <mapper resource="Com/Sun/Dao/UserMapper.xml"></mapper>
        </mappers>
    </configuration>
    
  3. 编写接口

    public interface UserMapper {
       public List<User> selectUser();
    }
    
  4. 编写Mapper.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">
    <mapper namespace="Com.Sun.Dao.UserMapper">
    
        <select id="getAllUser" resultType="Com.Sun.pojo.User">
            select * from mybatis.user;
        </select>
    </mapper>
    
  5. MybatisUtils

    package com.Sun.Uitls;
    //sqlSessionFactory --> sqlSession
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import java.io.IOException;
    import java.io.InputStream;
    
    public class MybatisUtils {
        static SqlSessionFactory sqlSessionFactory = null;
        static {
            try {
                //使用Mybatis第一步 :获取sqlSessionFactory对象
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例.
        // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
        public static SqlSession getSqlSession(){
            //SqlSession sqlSession = sqlSessionFactory.openSession();
            //return  sqlSession;
            return sqlSessionFactory.openSession();
        }
    }
    
  6. 测试

    package Com.Sun.Test;
    
    import Com.Sun.Dao.UserMapper;
    import Com.Sun.Until.MybatisUtils;
    import Com.Sun.pojo.User;
    import org.apache.ibatis.session.SqlSession;
    import java.util.List;
    
    public class MyTest {
        public static void main(String[] args) {
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> allUser =mapper.getAllUser();
            for (User user : allUser) {
                System.out.println(user);
            }
            sqlSession.close();
        }
    }
    

12.2、Mybatis-Spring

引入Spring之前需要了解 mybatis-spring包中的一些重要类;

mybatis-spring官网

什么是 MyBatis-Spring?

MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。

知识基础

在开始使用 MyBatis-Spring 之前,你需要先熟悉 Spring 和 MyBatis 这两个框架和有关它们的术语。这很重要

MyBatis-Spring 需要以下版本:

MyBatis-SpringMyBatisSpring 框架Spring BatchJava
2.03.5+5.0+4.0+Java 8+
1.33.4+3.2.2+2.1+Java 6+

如果使用 Maven 作为构建工具,仅需要在 pom.xml 中加入以下代码即可:

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis-spring</artifactId>
   <version>2.0.2</version>
</dependency>

整合方式一

  1. 引入配置文件

    <?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">
    </beans>
    
  2. 编写数据源配置

    <!--配置数据源:数据源有非常多,可以使用第三方的,也可使使用Spring的-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=ture&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=Asia/Shanghai"/>
        <property name="username" value="root"/>
        <property name="password" value="cgj532416"/>
    </bean>
    
  3. sqlSessionFactory

    <!--配置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/Sun/Dao/UserMapper.xml"/>
    </bean>
    
  4. sqlSessionTemplate

    <!--注册sqlSessionTemplate , 关联sqlSessionFactory-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--利用构造器注入,没有set注入,只能使用构造器注入-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
    
  5. 需要给接口加实现类【新加的】

    public class UserDaoImpl implements UserMapper {
        //sqlSession不用我们自己创建了,Spring来管理
        private SqlSessionTemplate sqlSession;
        public void setSqlSession(SqlSessionTemplate sqlSession) {
            this.sqlSession = sqlSession;
        }
        public List<User> getAllUser() {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            return mapper.getAllUser();
        }
    }
    
  6. 将自己写的实现类,注入到Spring中

    <bean id="userDao" class="Com.Sun.Dao.UserDaoImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
    
  7. 测试使用即可

    public static void main(String[] args) throws Exception{
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        UserMapper userDao = (UserMapper) context.getBean("userDao");
        List<User> allUser = userDao.getAllUser();
        for (User user : allUser) {
            System.out.println(user.toString());
        }
    }
    

结果成功输出!现在我们的Mybatis配置文件的状态!发现都可以被Spring整合!

为了给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">
<configuration>
 <typeAliases>
     <package name="Com.Sun.pojo"/>
 </typeAliases>

<!-- <settings>
 	<setting></setting>
 </settings> -->
</configuration>

**整合实现二 **

mybatis-spring1.2.3版以上的才有这个 .

官方文档截图 :

dao继承Support类 , 直接利用 getSqlSession() 获得 , 然后直接注入SqlSessionFactory . 比起方式1 , 不需要管理SqlSessionTemplate , 而且对事务的支持更加友好 . 可跟踪源码查看

1078856-20170205160357354-490660449

测试:

  1. 将我们上面写的UserDaoImpl修改一下

    public class UserDaoImpl2 extends SqlSessionDaoSupport implements UserMapper {
        @Override
        public List<User> getAllUser() {
            UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
            List<User> allUser = mapper.getAllUser();
            return allUser;
        }
    }
    
  2. 修改bean的配置

    <bean id="userDao" class="Com.Sun.Dao.UserDaoImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
    
  3. 测试

    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userDao = (UserMapper) context.getBean("userDao");
        for (User user : userDao.getAllUser()) {
            System.out.println(user);
        }
    }
    

总结 : 整合到spring以后可以完全不要mybatis的配置文件,除了这些方式可以实现整合之外,我们还可以使用注解来实现,这个等我们后面学习SpringBoot的时候还会测试整合!

13、声明式事务

13.1、回顾事务

  • 把一组业务当成一个业务来做;要么都成功,要么都失败!
  • 事务在项目开发中,十分重要,涉及到数据的一致性问题,不能马虎
  • 确保完整性和一致性

事务的ACID原则

  • 原子性(atomicity)
    • 事务是原子性操作,由一系列动作组成,事务的原子性确保动作要么全部完成,要么完全不起作用
  • 一致性(consistency)
    • 一旦所有事务动作完成,事务就要被提交。数据和资源处于一种满足业务规则的一致性状态中
  • 隔离性(isolation)
    • 多个业务可能操作同一个资源,防止数据损坏
  • 持久性(durability)
    • 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化的写到存储器中!

13.2、Spring中的事务管理

  • 声明式事务:AOP

    • 一般情况下比编程式事务好用。
    • 将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理。
    • 将事务管理作为横切关注点,通过aop方法模块化。Spring中通过Spring AOP框架支持声明式事务管理
  • 编程式事务:需要在代码中,进行事务的管理

    • 将事务管理代码嵌到业务方法中来控制事务的提交和回滚
    • 缺点:必须在每个事务操作业务逻辑中包含额外的事务管理代码
  • 使用Spring管理事务,注意头文件的约束导入 : tx

    xmlns:tx="http://www.springframework.org/schema/tx"
    
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    
  • 事务管理器

    • 无论使用Spring的哪种事务管理策略(编程式或者声明式)事务管理器都是必须的。
    • 就是 Spring的核心事务管理抽象,管理封装了一组独立于技术的方法。
  • JDBC事务

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
  • 配置事务的通知

    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--配置哪些方法使用什么样的事务,配置事务的传播特性-->
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="search*" propagation="REQUIRED"/>
            <tx:method name="get" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    
  • spring事务传播特性:

    事务传播行为就是多个事务方法相互调用时,事务如何在这些方法间传播。spring支持7种事务传播行为:

    • propagation_requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中,这是最常见的选择。
    • propagation_supports:支持当前事务,如果没有当前事务,就以非事务方法执行。
    • propagation_mandatory:使用当前事务,如果没有当前事务,就抛出异常。
    • propagation_required_new:新建事务,如果当前存在事务,把当前事务挂起。
    • propagation_not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
    • propagation_never:以非事务方式执行操作,如果当前事务存在则抛出异常。
    • propagation_nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作
  • 配置AOP(导入aop的头文件!)

    <!--配置aop织入事务-->
    <aop:config>
        <aop:pointcut id="txPointcut"  expression="execution(* Com.Sun.dao.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>
    

思考:

为什么需要事务?

  • 如果不配置,可能存在数据提交不一致的情况;
  • 如果我们不在Spring中去配置声明式事务,我们需要在代码中手动配置事务!
  • 事务在项目开发过程非常重要,涉及到数据的一致性的问题,不容马虎!

即使再小的帆也能远航

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值