一. Spring

Spring的基本组成:

1、最完善的轻量级核心框架。

2、通用的事务管理抽象层。

3、JDBC抽象层。

4、集成了Toplink, Hibernate, JDO, and iBATIS SQL Maps。

5、AOP功能。

6、灵活的MVC Web应用框架。

文档: https://docs.spring.io/spring-framework/docs/5.3.5/reference/html/index.html

各个版本: https://docs.spring.io/spring-framework/docs/

API: https://docs.spring.io/spring-framework/docs/5.3.5/javadoc-api/

二. 导入依赖

  • 直接在pom.xml中配置sping-webmvc依赖, 会自动导入其他依赖, 很方便
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

三. 优点

  • Spring是一个开源的免费的框架(容器)!
  • 轻量级的, 非入侵式的框架!
  • 控制反转 (IOC), 面向切面编程 (AOP)!
  • 支持事务的处理, 对框架整合的支持!

总结: Spring是一个轻量级的控制反转(IOC)和面向切面(AOP)的容器框架!

public class UserServiceImpl implements UserService {
private UserDao userDao; //利用set进行动态实现值的注入
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
} @Override
public void getUser() {
userDao.getUser();
}
}
  • 之前, 程序是主动创建对象, 控制权在程序员手上
  • 使用了set注入后, 程序不再具有主动性, 而是变成了被动的接收对象
  • 这种思想, 从本质上解决了问题, 我们程序员不用再去管理对象的创建了, 系统的耦合度大大降低, 可以更加专注在业务的实现上! 这是IOC的原型!

四. IOC创建对象的方式

4.1 无参构造

<!--无参构造方法-->
<bean id="user" class="com.dz.entity.User">
<property name="name" value="张三"/>
<property name="age" value="18"/>
<property name="gender" value="true"/>
</bean>

4.2 有参构造(3种方式)

4.2.1 下标
<!--有参构造方法-->
<!--方法一: 下标赋值-->
<bean id="user" class="com.dz.entity.User">
<constructor-arg index="0" value="张三"/>
<constructor-arg index="1" value="18"/>
<constructor-arg index="2" value="true"/>
</bean>
4.2.2 类型
<!--方法二: 通过类型创建, 不建议使用-->
<bean id="user" class="com.dz.entity.User">
<constructor-arg type="java.lang.String" value="张三"/>
<constructor-arg type="java.lang.Integer" value="18"/>
<constructor-arg type="java.lang.Boolean" value="true"/>
</bean>
4.2.3 参数名
<!--方法三: 直接通过参数名设置-->
<bean id="user" class="com.dz.entity.User">
<constructor-arg name="name" value="张三"/>
<constructor-arg name="age" value="18"/>
<constructor-arg name="gender" value="true"/>
</bean>
  • 总结: 在配置文件加载的时候, 容器中管理的对象就已经初始化了

五. Spring配置

5.1 别名

<!--如果添加了别名, 我们也可以通过别名获取到这个对象-->
<alias name="user" alias="userNew"/>

5.2 Bean的配置

<!--如果添加了别名, 我们也可以通过别名获取到这个对象-->
<!--<alias name="user" alias="userNew"/>-->
<!--无参构造方法
id: bean 的唯一标识符, 也就是我们学的对象名
class: bean 对象所对应的全限定名: 包名 + 类型
name: 也是别名, 而且name 可以同时取多个别名
-->
<bean id="user" class="com.dz.entity.User" name="user2 user3,user4;user5">
<property name="name" value="张三"/>
<property name="age" value="18"/>
<property name="gender" value="true"/>
</bean>

5.3 import

  • 一般用于团队开发使用, 可以将多个配置文件, 导入合并为一个
  • 正规xml全称是: applicationContext.xml , 把所有其他的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"> <import resource="beans.xml"/>
<import resource="beans2.xml"/>
</beans>

六. 依赖注入

6.1 构造器注入[见第四节]

6.2 Set方式注入 [重点]

  • 依赖注入: Set注入!

    • 依赖: bean对象的创建依赖于容器
    • 注入: bean对象中的所有属性, 由容器来注入

环境搭建

  1. 复杂类型
package com.dz.entity;

public class Address {
private String address; public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
}
}
  1. 真实测试对象
package com.dz.entity;

import java.util.*;

public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbies;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info; //Getter Setter...
}
  1. 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="student" class="com.dz.entity.Student">
<property name="name" value="张三"/>
</bean>
</beans>
  1. 测试类
import com.dz.entity.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//Student student = (Student) context.getBean("student");
Student student = context.getBean("student",Student.class);
System.out.println(student.getName());
}
}

完善注入信息

<?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.dz.entity.Address">
<property name="address" value="郑州"/>
</bean> <bean id="student" class="com.dz.entity.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="hobbies">
<list>
<value>看书</value>
<value>游戏</value>
<value>看剧</value>
</list>
</property>
<!--五: Map-->
<property name="card">
<map>
<entry key="身份证" value="123456"/>
<entry key="银行卡" value="123456"/>
</map>
</property>
<!--六: Set-->
<property name="games">
<set>
<value>lol</value>
<value>cf</value>
</set>
</property>
<!--七: null-->
<property name="wife">
<null/>
</property>
<!--八: Properties-->
<property name="info">
<props>
<prop key="driverClassName">com.mysql.jdbc.Driver</prop>
<prop key="url">jdbc:mysql://localhost:3306/</prop>
<prop key="username">root</prop>
<prop key="password">8031</prop>
</props>
</property>
</bean>
</beans>

6.3 扩展方式注入(p, c 命名空间)

  • 我们可以使用p命名空间和c命令空间进行注入
6.3.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"
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命名空间注入, 可以直接注入属性的值: property-->
<bean id="user" class="com.dz.entity.User" p:name="张三" p:age="18"/>
<!--c命名空间注入, 通过构造器注入: constructor-args-->
<bean id="user2" class="com.dz.entity.User" c:name="李四" c:age="19"/>
</beans>
6.3.2 测试
@Test
public void test2() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user2",User.class);
System.out.println(user.toString());
}
  • 注意: p命名和c命名空间不能直接使用, 需要导入xml约束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"

6.4 bean的作用域

  1. 单例模式 scope="singleton" , Spring默认机制
<bean id="user" class="com.dz.entity.User" p:name="张三" p:age="18" scope="singleton"/>
  1. 原型模式 scope="prototype", 每次从容器中get的时候, 都会产生一个新对象
<bean id="user2" class="com.dz.entity.User" c:name="李四" c:age="19" scope="prototype"/>
  1. 其余的 request, session, application 这些只能在WEB开发中用到

七. Bean的自动装配(属性)

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

在Spring中有三种自动装配的方式

  1. 在xml中显示的配置 (autowire="byName"或者autowire="byType")
  2. 在java中显示的配置
  3. 使用注解 隐式的自动装配bean[重要]

7.1 测试

环境搭建: 一个人 有两个宠物

7.2 byName自动装配

<!--byName: 会自动在容器上下文中查找和自己对象属性 名字 相同的bean id-->
<bean id="person" class="com.dz.entity.Person" autowire="byName">
<property name="name" value="张三"/>
</bean>

7.3 byType自动装配

<!--byType: 会自动在容器上下文中查找和自己对象属性 类别 相同的bean-->
<bean id="person" class="com.dz.entity.Person" autowire="byType">
<property name="name" value="张三"/>
</bean>

小结:

  • byName的时候, 需要保证所有bean的id唯一, 且这个bean的 id需要和自己对象属性名相同
  • 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>
7.4.1 @Autowired注解
  • 直接在属性上使用即可

科普:

  • @nullable: 字段标记了这个注解, 说明这个字段可以为nul
public @interface Autowired {
boolean required() default true;
}

测试代码

public class Person {
//如果显示定义了Autowired的required = false,说明这个对象可以为null,否则不为空
@Autowired(required = false)
private Dog dog;
@Autowired
private Cat cat;
private String name;
}
  • 如果@Autowired自动装配的环境比较复杂, 自动装配无法通过一个注解(@Autowired) 完成的时候, 可以使用@Qualifier(value="xxx")去配合@Autowired, 指定一个唯一的bean对象注入
public class Person {
@Autowired(required = false)
private Dog dog;
@Autowired
@Qualifier(value = "cat123")
private Cat cat;
private String name;
}
7.4.2 @Resource注解
public class Person {
@Resource(name = "dog123")
private Dog dog;
@Resource
private Cat cat;
private String name;

小结:

@Resource和@Autowired的区别:

  • 都是用来自动装配的, 都可以放在属性字段上
  • @Autowired通过byType实现 [常用]
  • @Resource默认通过byName实现, 如果找不到名字, 则通过byType实现, 如果类型也找不到, 就报错! [常用]
  • 执行顺序不同: @Autowired通过byType实现. @Resource默认通过byName实现

八. 使用注解开发

  • 在Spring4之后, 想要使用注解开发, 必须要保证 aop 的包已导入
  • 使用注解需要
    • 导入context约束
    • 增加注解支持
    • 指定要扫描的包
<?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/>
<!--指定要扫描的包, 这个包下的注解就会生效-->
<context:component-scan base-package="com.dz"/> </beans>
  1. bean

  2. 属性如何注入

    基本数据类型: 在属性名上写@Value

    引用数据类型: 在属性名上写@Autowired或@Resource

    package com.dz.pojo;
    
    import org.springframework.beans.factory.annotation.Value;
    
    public class User {
    //等价于 <property name="name" value="张三"/>
    @Value("张三")
    private String name; public String getName() {
    return name;
    } public void setName(String name) {
    this.name = name;
    }
    }
  3. 衍生的注解

    @Component (通用组件)有几个衍生注解, 我们在WEB开发过程中, 会按照mvc三层架构分层

    1. dao: @Repository
    2. service: @Service
    3. controller: @Controller

      这四个注解都是一样的, 都是代表将某个类注册到Spring容器中, 装配bean
  4. 自动装配

    @Autowired: 通过类型 自动装配
    如果@Autowired不能唯一自动装配上属性,则需要@Qualifier(value="xxx")
    @Nullable: 字段标记了这个注解, 说明这个字段可以为空
    @Resource: 通过名字、类型 自动装配
  5. 作用域

    package com.dz.pojo;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Component; //等价于 <bean id="user" class="com.dz.pojo.User"/>
    //@Component 组件
    @Component
    @Scope("prototype")
    public class User {
    //等价于 <property name="name" value="张三"/>
    @Value("张三")
    private String name; public String getName() {
    return name;
    } public void setName(String name) {
    this.name = name;
    }
    }
  6. 小结

    xml与注解对比:

    1. xml更加万能, 适用于任何场合, 维护简单方便
    2. 注解 不是自己类使用不了, 维护相对复杂

    xml与注解最佳实践:

    1. xml用来管理bean
    2. 注解只负责属性的注入
    3. 要注意使用注解前, 必须让注解生效, 开启注解的支持

九. 使用Java的方式配置Spring

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

实体类

package com.dz.pojo;

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

public class User {

    @Value("张三")
private String name; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}

配置文件

package com.dz.config;

import com.dz.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; //@Configuration也会被Spring容器托管,注册到容器中, 因为其本身也是一个@Component(用于标记的)
//@Configuration代表这是一个配置类, 就和之前的beans.xml一样
@Configuration
@ComponentScan(basePackages = "com.dz")//扫描com.dz下的文件
@Import(Config2.class)//把Config2导入进来
public class AppConfig {
//注册一个bean, 就相当于我们之前写的一个bean标签
//方法名相当于 以前bean标签里的id属性
//方法返回值, 想当于bean标签中的class属性
@Bean
public User user() {
return new User();//就是返回要注入到bean的对象
}
}

测试类

import com.dz.config.AppConfig;
import com.dz.pojo.User;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class MyTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
User user = (User) context.getBean("user");
System.out.println(user.getName());
}
}

十. 代理模式

为什么要学习代理模式? 因为这就是SpringAOP的底层?

[SpringAOP 和 SpringMVC 面试必问]

代理模式的分类:

  • 静态代理
  • 动态代理

10.1 静态代理

角色分析:

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

代码步骤:

  • 接口

    • package com.dz.demo01;
      
      //租房
      public interface Rent {
      void rent();
      }
  • 真实角色

    • package com.dz.demo01;
      
      //房东
      public class Landlord implements Rent{
      @Override
      public void rent() {
      System.out.println("房东要出租房子!");
      }
      }
  • 代理角色

    • package com.dz.demo01;
      
      //代理
      public class Proxy implements Rent{
      private Landlord landlord; public Proxy() {
      } public Proxy(Landlord landlord) {
      this.landlord = landlord;
      } @Override
      public void rent() {
      landlord.rent();
      }
      //看房
      public void seeHouse() {
      System.out.println("中介带你去看房");
      }
      //收中介费
      public void charge() {
      System.out.println("中介收中介费");
      }
      }
  • 客户访问代理角色

    • package com.dz.demo01;
      
      //租户
      public class Tenant {
      public static void main(String[] args) {
      //创建房东对象
      Landlord landlord = new Landlord();
      //代理: 中介帮房东出租房子, 但是一般会有一些附属操作, 例如收钱等
      Proxy proxy = new Proxy(landlord);
      //中介开始向外出租房子, 租客不用找房东, 直接找中介即可
      proxy.rent();
      }
      }

代理模式的优点:

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

缺点:

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

10.2 加深理解

  • 在不改变原有代码的基础上, 又通过代理增加了新的功能

10.3 动态代理

  • 动态代理和静态代理角色一样
  • 动态代理的代理类是动态生成的, 不是我们直接写好的
  • 动态代理分为两大类:
    • 基于接口---JDK代理[我们一般使用这个]
    • 基于类: cglib
    • java 字节码实现: javasist

Proxy类 和 InvocationHandler接口

  • Proxy提供了创建动态代理类和实例的静态方法, 我们最常用的是newProxyInstance方法, 这个方法接收以下三个参数

    • loader:一个classloader对象,定义了由哪个classloader对象对生成的代理类进行加载
    • interfaces:一个interface对象数组,表示我们将要给我们的代理对象提供一组什么样的接口,如果我们提供了这样一个接口对象数组,那么也就是声明了代理类实现了这些接口,代理类就可以调用接口中声明的所有方法。
    • h:一个InvocationHandler对象,表示的是当动态代理对象调用方法的时候会关联到哪一个InvocationHandler对象上,并最终由其调用。
  • InvocationHandler接口是proxy代理实例的调用处理程序实现的一个接口,每一个proxy代理实例都有一个关联的调用处理程序;在代理实例调用方法时,方法调用被编码分派到调用处理程序的invoke方法。

动态代理的好处:

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

动态代理实现:

package com.dz.demo04;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy; //我们用这个类自动生成代理类
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);
} //处理代理实例, 并返回结果
@Override
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("执行了" + msg + "方法");
}
}

测试:

package com.dz.demo04;

import com.dz.demo02.UserService;
import com.dz.demo02.UserServiceImpl; public class Client {
public static void main(String[] args) {
//1. 要代理的接口
UserService userService = new UserServiceImpl();
//2. 创建生成代理类的对象
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//3. 设置要代理的接口
pih.setTarget(userService);
//4. 动态生成代理类对象
UserService proxy = (UserService) pih.getProxy();
//5. 通过代理调用方法
proxy.insert();
}
}

十一. AOP

11.1 什么是AOP

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

11.2 作用

  • 将日志记录,性能统计,安全控制,事务处理,

    异常处理

    等代码从业务逻辑代码中划分出来,通过对这些行为的分离,我们希望可以将它们独立到非指导业务逻辑的方法中,进而改变这些行为的时候不影响业务逻辑的代码。

    • Aspect(切面): Aspect 声明类似于 Java 中的类声明,在 Aspect 中会包含着一些 Pointcut 以及相应的 Advice。
    • Joint point(连接点):表示在程序中明确定义的点,典型的包括方法调用,对类成员的访问以及异常处理程序块的执行等等,它自身还可以嵌套其它 joint point。
    • Pointcut(切点):表示一组 joint point,这些 joint point 或是通过逻辑关系组合起来,或是通过通配、正则表达式等方式集中起来,它定义了相应的 Advice 将要发生的地方。
    • Advice(增强):Advice 定义了在 Pointcut 里面定义的程序点具体要做的操作,它通过 before、after 和 around 来区别是在每个 joint point 之前、之后还是代替执行的代码。
    • Target(目标对象):织入 Advice 的目标对象.。
    • Weaving(织入):将 Aspect 和其他对象连接起来, 并创建 Adviced object 的过程

11.3 使用Spring实现AOP

11.3.1 使用AOP织入, 需要导入一个依赖包[重点]
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
11.3.2 方式一: 使用Spring的API接口实现AOP
<bean id="userService" class="com.dz.service.UserServiceImpl"/>
<bean id="beforeLog" class="com.dz.log.BeforeLog"/>
<bean id="afterLog" class="com.dz.log.AfterLog"/> <!--方式一: 使用原生的Spring API接口-->
<!--配置aop: 需要导入aop的约束-->
<aop:config>
<!--切入点: expression表达式 1. execution()表达式主体 (要执行的位置!*(返回类型) *(包名) *(类名) *(方法名) *(参数))-->
<aop:pointcut id="pointcut" expression="execution(* com.dz.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加-->
<aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
11.3.3 方式二: 自定义类实现AOP(主要是切面定义)
<bean id="diy" class="com.dz.diy.DiyPointCut"/>
<!--方式二: 自定义类-->
<aop:config>
<!--自定义切面 ref: 要引用的类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="pointcut" expression="execution(* com.dz.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="pointcut"/>
<aop:after method="after" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
11.3.4 方式三: 使用注解实现AOP
<!--方式三: 使用注解-->
<bean id="annotationPointCut" class="com.dz.diy.AnnotationPointCut"/>
<!--开启注解支持 JDK(默认 proxy-target-class="false") cglib(proxy-target-class="true")-->
<aop:aspectj-autoproxy/>

package com.dz.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.dz.service.UserServiceImpl.*(..))")
public void before() {
System.out.println("====方法执行前");
} @After("execution(* com.dz.service.UserServiceImpl.*(..))")
public void after() {
System.out.println("====方法执行后");
} @Around("execution(* com.dz.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("====环绕前====");
Signature signature = pjp.getSignature();//获得签名
System.out.println(signature);
Object proceed = pjp.proceed(); //执行方法
System.out.println("====环绕后====");
}
}

十二. 整合MyBatis

  • 步骤

    1. 导入相关jar包

      • junit 4.12
      • mysql-connector-java 5.1.47
      • mybatis 3.5.3
      • spring相关的 (spring-webmvc 5.3.5, spring-jdbc 5.3.5)
      • aop织入(aspectjweaver 1.96)
      • mybatis-spring 2.06
      • lombok 1.18.16
    2. 编写配置文件
    3. 测试
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>provided</scope>
</dependency>
  • 使用lombok不仅要导入依赖, 还要在IDEA中手动下载lombok插件
  • Settings > Plugins > Marketplace > 输入lombok

12.1 回忆MyBatis

  • 编写实体类
  • 编写核心配置文件 mybatis-config.xml ,主要配置:
    1. 导入jdbc.properties数据库连接配置文件
    2. 设置实体类别名
    3. 环境配置: 数据库事务控制类型, 连接池
    4. 注册mapper文件
  • 编写接口
  • 编写Mapper.xml
  • 编写MyBatis工具类并测试

12.2 MyBatis-Spring

  1. 编写数据源配置
  2. sqlSessionFactory
  3. SqlSessionTemplate
  4. 需要给接口加实现类
  5. 将自己写的实现类注入到Spring中
  6. 测试

十三. 事务

13.1 概念

  • 事务(Transaction),一般是指要做的或所做的事情。在计算机术语中是指访问并可能更新数据库中各种数据项的一个程序执行单元(unit)。事务通常由高级数据库操纵语言或编程语言(如SQL,C++或Java)书写的用户程序的执行所引起,并用形如begin transactionend transaction语句(或函数调用)来界定。事务由事务开始(begin transaction)和事务结束(end transaction)之间执行的全体操作组成。
  • 事务是恢复和并发控制的基本单位。
  • 事务应该具有4个属性:原子性、一致性、隔离性、持久性。这四个属性通常称为ACID特性
    • 原子性(atomicity):一个事务是一个不可分割的工作单位,事务中包括的操作要么都做,要么都不做
    • 一致性(consistency):事务必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的
    • 隔离性(isolation):一个事务的执行不能被其他事务干扰。即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰
    • 持久性(durability):持久性也称永久性(permanence),指一个事务一旦提交,它对数据库中数据的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响

13.2 Spring中的事务管理

  • 声明式事务: AOP
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<!--配置声明式事务 引入一个事务管理器,其中依赖dataSource, 借以获得连接, 进而控制事务逻辑-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务通知-->
<tx:advice id="txManager" transaction-manager="transactionManager">
<!--事务属性 给哪些方法配置事务-->
<!--配置事务的传播特性 propagation-->
<tx:attributes>
<!--以User结尾的方法, 切入此方法时, 采用对应事务实行-->
<!--REQUIRED 默认创建一个新的事务-->
<tx:method name="inset" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<!--以query开头的方法, 切入此方法时, 采用对应事务实行-->
<tx:method name="query" read-only="true"/>
<!--剩余的所有方法-->
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.dz.mapper.*.*(..))"/>
<aop:advisor advice-ref="txManager" pointcut-ref="txPointCut"/>
</aop:config>
  • 编程式事务: 需要在代码中,进行事务管理

为什么需要事务?

  • 如果不配置事务, 可能存在数据提交不一致的情况
  • 如果我们不在Spring中去配置声明式事务, 我们就要在代码中手动配置事务
  • 事务在项目的开发中十分重要, 涉及到数据的一致性和完整性问题

4_Spring的更多相关文章

随机推荐

  1. docker容器数据管理

    Docker容器数据卷 Docker中的数据可以存储在类似于虚拟机磁盘的介质中,在Docker中称为数据卷(Data Volume). 数据卷可以用来存储Docker应用的数据,也可以用来在Docke ...

  2. ELK 日志分析系统的部署

    一.ELK简介 ElasticSearch介绍Elasticsearch是一个基于Lucene的搜索服务器. 它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口. Elasti ...

  3. raspberrypi系统在加入k8s作为node节点时遇到的问题

    新买的树莓派4b到货后就迫不及待的烧录上raspberrypi系统,将新派加入我的k8s集群,期间遇到了点小挫折,好歹也一个一个解决了: 一.kubelet版本不对导致无法加入k8s集群 在执行kub ...

  4. Object类中wait代餐方法和notifyAll方法和线程间通信

    Object类中wait代餐方法和notifyAll方法 package com.yang.Test.ThreadStudy; import lombok.SneakyThrows; /** * 进入 ...

  5. HashTable集合和练习题_计算一个字符串中每一个字符出现的次数

    HashTable集合 /** * java.util.Hashtable<K,V>集合 implement Map<K,V>接口 * Hashtable:底层也是一个哈希表, ...

  6. 可以级联的以太网远程IO模块的优点与适用场景

    可以级联的以太网远程IO模块的优点与具体的适用场景 对于数据采集控制点是按照线性分布的场景,比如智慧园区的路灯.桥梁.路灯.数字化工厂.停车场车位监测.智慧停车场.智能停车架.楼宇自动控制系统等场景, ...

  7. Java---注解与反射

    前言 近期在学习SSM框架的过程中发现在SSM框架中大量用到了反射与注解的知识,要想学好SSM框架,必须将注解与反射熟记于心,尤其是对Java反射机制的理解. 对于我这种记性不好的人来说"基 ...

  8. 提交代码的其他方式,不单单只有git

    1.  xftp提交代码至服务器,直接连接服务器(如果使用可以直接到官网下载一个试用版或者家庭教育版的,本人不推荐使用破解版毕竟是直接和公司服务器对接出问题不好交代) // https://www.n ...

  9. FutureTask源码深度剖析

    FutureTask源码深度剖析 前言 在前面的文章自己动手写FutureTask当中我们已经仔细分析了FutureTask给我们提供的功能,并且深入分析了我们该如何实现它的功能,并且给出了使用Ree ...

  10. Luogu2018 消息传递 (树形DP)

    贪心优先子树较多者. #include <iostream> #include <cstdio> #include <cstring> #include <a ...