Spring 使用
spring 学习
1.Spring
1.1 简介
- Spring框架即以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日,发布了1.0正式版
- Spring 是一个开源框架,最早由 Rod Johnson 发起。Spring 为简化企业级开发而生,使 用 Spring 开发可以将 Bean 对象交给 Spring 容器来管理,这样使得很多复杂的代码在 Spring 中开发会变得非常的优雅和简洁,有效的降低代码的耦合度,极大的方便项目的后期维护、 升级和扩展。
- spring 理念:使现在的技术更容易使用,本身是一个大杂烩,整合了现有技术框架
官网:https://spring.io/projects/spring-framework#learn
官方下载地址:https://repo.spring.io/release/org/springframework/spring/
github 地址:https://github.com/spring-projects/spring-framework
1.2 优点
- spring 是一个开源的免费的框架(容器)
- spring 是一个轻量级;非入侵式框架(不会影响原来的代码)基于 Spring 开发的应用中的对象可以不依赖于 Spring 的 API。
- 控制反转(IOC),面向切面编程(AOP)
- 支持事务处理,对框架整合的支持
总结:Spring 就是一个轻量级的控制反转(IOC)和面向切面编程框架(AOP)框架
1.3 组成
1.4 拓展
- spring boot
- 一个快速开发的脚手架
- 基于 springboot 可以快速的开发单体微服务
- 约定大于配置
- spring cloud
- spring cloud 是基于 springboot 实现的
弊端:发展了太久之后,变得配置十分繁琐,人称“配置地域”
2.IOC 推导
- UserDao 接口
- UserDaoImpl 实现类
- UserService 业务接口
- UserServiceImpl 业务实现类
在我们之前的业务层,用户的需求可能会影响我们原来的代码,我们需要根据用户需求修改原代码。如果程序代码量十分大,修改一次成本代价十分昂贵。
我们使用 Set 接口实现
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本质
控制反转 IOC(Inversion of Controller) 是一种设计思想,DL(依赖注入)是实现 IOC 的一种方法。也有人认为DI 只是 IOC 的一种说法,没有 IOC 的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转义到第三方,个人认为所谓控制反转:是依赖对象的方式反转。
采用 XML 方式配置 Bean 的时候,Bean 的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean 的定义信息直接以注解的形式定义在实现类中,从而达到零配置的目的。
控制反转是一种通过描述(XML 或注解)通过第三方去生产或获取特点对象的方式。spring 中实现控制反转的是 IOC 容器,其实现方法是依赖注入。
3.hello Spring
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
<?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 类型()
Hello hello = new Hello()
bean 代表对象 new Hello();
id=变量名
class = new 的对象
property 相当于给对象中属性设置一个值
-->
<bean id="hello" class="com.study.pojo.Hello">
<property name="str" value="Spring"/>
</bean>
</beans>
public class MyTest {
public static void main(String[] args) {
//获取 spring 上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//对象都在 spring 中管理,要使用直接取出来
Hello hello =(Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
思考问题?
- Hello 对象是谁创建的?
Hello 对象是由 Spring 创建的 - Hello 对象的属性是怎么设置的?
Hello 对象的属性是由 Spring 容器设置
这个过程就叫控制反转:
控制:谁来控制对象的创建,传统应用程序的对象是程序本身控制创建的,使用 spring 后,对象由 spring 创建
反转:程序本身不创建对象,而变成被动接受对象
依赖注入:就是利用 set 方法来进行注入
IOC 是一种思想,有主动变成被动接收
所谓 IOC 一句话就是,对象由 spring 创建,管理,装配
4.IOC 创建对象的方式
- 使用无参构造创建对象,默认
- 假设使用有参构造创建
- 下标赋值
<bean id="user" class="com.study.pojo.User">
<constructor-arg index="0" value="张三"/>
</bean>
1. 通过类型创建(不建议使用,二个同类型参数无法创建)
<bean id="user" class="com.study.pojo.User">
<constructor-arg type="java.lang.String" value="李四"/>
</bean>
1. 通过参数名赋值
<bean id="user" class="com.study.pojo.User">
<constructor-arg name="name" value="王五"/>
</bean>
总结:在配置文件加载的时候,其中容器中管理的所有对象就初始化了!
5.spring 配置
5.1 别名
<!-- 如果添加了别名,也可以使用别名取到-->
<alias name="user" alias="userNew"/>
5.2 Bean 配置
<!-- id:bean 的唯一标识符,也就是相当于我们学的对象名
class: bean 对象对应的全限定名:包名+类名
name:也是别名,而且 name 可以同时取多个别名
-->
<bean id="user" class="com.study.pojo.User" name="user1,user2">
<property name="name" value="王五"/>
</bean>
5.3 import
一般用于团队开发使用,他可以将多个配置文件导入合并为一个
假设项目中多个人开发 ,这两个人需要注册到不同 bean 中,可以利用 import 将所有人 beans.xml 合并为一个总的如: applicationContext.xml
- 张三
- 李四
- applicationContext.xml
<import resource="beans.xml"/>
<import resource="beans2.xml"/>
6.依赖注入
6.1 构造器注入(如上)
6.2 set 方式注入
- 依赖注入:set 注入
- 依赖:bean 对象的创建依赖于容器
- 注入:bean对象的所有属性,由容器来注入
【环境搭建】
- 复杂类型
public class Address {
private String addr;
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
}
- 测试对象
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String, String> map;
private Set<String> games;
private String wife;
private Properties info;
}
- 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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="address" class="com.study.pojo.Address">
<property name="addr" value="北京"/>
</bean>
<!-- 第一种普通属性注入,value-->
<bean id="student" class="com.study.pojo.Student">
<property name="name" value="张三"/>
<!-- 第二种,Bean 注入,用 ref 注入-->
<property name="address" ref="address"/>
<!-- 数组注入-->
<property name="books">
<array>
<value>语文</value>
<value>数学</value>
<value>英语</value>
</array>
</property>
<!-- list 注入-->
<property name="hobbys">
<list>
<value>学习</value>
<value>音乐</value>
<value>看书</value>
</list>
</property>
<!-- Map 注入-->
<property name="map">
<map>
<entry key="身份证" value="123456"/>
<entry key="银行卡" value="112455"/>
</map>
</property>
<!-- set 注入-->
<property name="games">
<set>
<value>LOL</value>
<value>KOL</value>
</set>
</property>
<!-- null注入-->
<property name="wife">
<null/>
</property>
<!-- properties 注入-->
<property name="info">
<props>
<prop key="学号">32666</prop>
<prop key="性别">男</prop>
<prop key="排名">2</prop>
</props>
</property>
</bean>
</beans>
- 测试
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());
}
}
6.3 其他方式
我们可以使用 p 命名空间和 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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- p 命名空间注入,可以直接注入属性的值 property set 注入 无参构造-->
<bean id="user" class="com.study.pojo.User" p:name="张三" p:age="18"/>
<!-- c命名空间,通过构造器注入 有参构造-->
<bean id="user2" class="com.study.pojo.User" c:name="李四" c:age="88"/>
</beans>
注意点:p 命令空间和 c 命名空间不能直接使用,需要导入 xml 约束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
6.4 bean 的作用域
1.单例模式(Spring 默认机制),只有一个对象
<bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>
2.原型模式,每次从容器中 get 都会产生一个新对象
<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
3.其余的 request、session、application 这些只能在 web 开发中使用到
7.Bean 的自动装配
- 自动装配是 Spring 满足 bean 依赖的一种方式
- Spring 会在上下文中自动寻找,并自动给 bean 装配属性
三种装配方式:
- 在 xml 文件中显示的配置
- 在 java 中显示配置
- 隐式的自动装配(重要)
7.1 测试
环境搭建:一个人有两个宠物
public class People {
private Cat cat;
private Dog dog;
private String name;
7.2 ByName 自动装配
<!--
byName:会自动在容器上下文中查找,和自己对象 set 方法后面的值对应的 beanid-->
<bean id="people" class="com.study.pojo.People" autowire="byName">
<property name="name" value="李四"/>
</bean>
7.3 ByType 自动装配
byType:会自动在容器上下文中查找,和自己对象类型相同的 bean-->
<bean id="people" class="com.study.pojo.People" autowire="byType">
<property name="name" value="李四"/>
</bean>
小结;
- ByName的时候,需要保证所有 beanid 唯一,并且 bean 需要和自动注入的属性的 set 方法值一致,也就是上面的 beanid=必须和属性的 set 方法后面的一致
- ByType的时候,需要保证所有 bean的 class 唯一,并且 bean 需要和自动注入的属性类型一致
7.4 使用注解实现自动装配
Jdk1.5支持注解,Spring2.5就支持注解
要使用注解须知:
- 导入约束。context约束
- 配置注解的支持 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>
Bean 对象依赖注入注解
**@Autowired **
用于对 Bean 的属性变量、方法及构造方法进行标注,完成 Bean 的自动注入处理。 @Autowired 按照 Bean 的类型进行装配。
**@Resource **
其作用与 Autowired 一样。其区别在于 @Autowired 按照 Bean 类型装配,而 @Resource 是可以按照 Bean ID 或者类型进行装配。
**@Qualifier **
与 @Autowired 注解配合使用,会将默认的按 Bean 类型装配修改为按 Bean 的实例名称装配,Bean 的实例名称由 @Qualifier 注解的参数指定。
**@Value **
可获取 Properties 文件中的值。也可以用于设置属性
//等价于<bean id="user" class="com.study.pojo.User"/>
@Component
public class User {
/**
* 等价于
* <bean id="user" class="com.study.pojo.User">
* <property name="name" value="张三"/>
*</bean>
*/
@Value("张三")
public String name;
}
- 小结:@Resource 和@Autowired 区别
- 都是用来自动装配的,都可以放在属性字段上
- @Autowired 通过 ByType 方式实现,而且必须要求这个对象存在
- @Resource 默认通过 Byname方式实现,找不到名字,则通过 ByType 实现,两种找不到报错
8.使用注解开发
在 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:component-scan base-package="com.study.pojo"/>
<!-- 可以省略注解驱动 <context:annotation-config/>-->
</beans>
注册 Bean 对象
**@Component **
可以使用此注解描述 Spring 中的 Bean,但它是一个泛化的概念,仅仅表示一个组件 (Bean),并且可以作用在任何层次。使用时只需将该注解标注在相应类上即可。下面用法一样,功能也是一样的,把某个类注册到 spring 容器中,装配 bean
//等价于<bean id="user" class="com.study.pojo.User"/>
@Component
public class User {
/**
* 等价于
* <bean id="user" class="com.study.pojo.User">
* <property name="name" value="张三"/>
*</bean>
*/
@Value("张三")
public String name;
}
**@Service **
通常作用在业务层(Service 层),用于将业务层的类标识为 Spring 中的 Bean,其功 能与 @Component 相同。
**@Repository **
于将数据访问层(DAO 层)的类标识为 Spring 中的 Bean,其功能与 @Component 相 同。
**@Controller **
通常作用在控制层(如 Spring MVC 的 Controller),用于将控制层的类标识为 Spring 中 的 Bean,其功能与 @Component 相同。
作用域
使用@Scope使用单例或原型模式
@Scope("singleton")//@Scope("prototype")
public class People {
小结:
xml 与注解:
- xml 更加万能,适合任何场合!维护简单方便
- 注解不是自己的类是用不了,维护相对复杂
xml与注解最佳实践:xml 用来管理 bean,注解只负责完成属性的注入,我们在使用过程中注意开启注解扫描,否则注解无法使用。
9.使用 java 方式配置 Spring
现在完全不使用 Spring的 xml 配置,全权交给 java 来做!
javaConfig 是 Spring的一个子项目,在Spring4 之后,它成为一个核心工程
- 实体类
//这里这个注解就是说嘛这个类被 Spring 接管了,注册到容器中
@Component
public class User {
private String name;
public String getName() {
return name;
}
@Value("张三")
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
- 配置类
//代表是一个配置类
@Configuration//也会被 spring 容器托管,注册到容器中,本身就是一个@Component
@Import(SpringConfig2.class)//将另一个配置类引入,这个作为主配置类
public class SpringConfig {
//注册一个 bean 相当于之前写的 bean 标签
// 这个方法的名字,就相当于 bean 标签中的 id 属性
//方法中的返回值,就相当于 bean 标签的 culass 属性
@Bean
public User user(){
return new User();//就是返回要注入到的 bean 的对象
}
}
- 测试
public class MyTest {
public static void main(String[] args) {
//完全适应配置类方式只能通过AnnotationConfigApplicationContext上下文来获取容器,通过配置类的 class 对象加载
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
User user = context.getBean("user", User.class);//方法名
System.out.println(user);
}
}
10 代理模式
为什么要学代理模式?
因为就是 SpringAop 的底层!(面试)
代理模式的分类:
- 静态代理
- 动态代理
10.1 静态代理
角色分析:
- 抽象角色:一般会使用接口或抽象类来解决
- 真实角色:被代理的角色
- 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作
- 客户:访问代理对象的人
实现步骤:
- 接口
//租房
public interface Rent {
public void rent();
}
- 真实角色
//房东
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东要出租房子");
}
}
- 代理角色
public class Proxy implements Rent{
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
@Override
public void rent() {
seeHouse();
host.rent();
fare();
}
//看房
public void seeHouse(){
System.out.println("中介带你看房");
}
//收费
public void fare(){
System.out.println("中介收费");
}
}
- 访问代理角色
//租房者
public class Client {
public static void main(String[] args) {
Host host = new Host();
Proxy proxy = new Proxy(host);
proxy.rent();
Thread thread = new Thread();
thread.start();
}
}
代理模式好处:
- 可以使真实角色操作更加纯粹,不用关注公共业务
- 公共也交给代理角色!实现了业务分工,耦合性降低
- 公共业务发生扩展时候,方便集中管理,这样原有业务代码无须改动,只需去增加代理角色内的相关业务,即可实现
缺点:
- 一个真实角色就会产生一个代理角色;代码量翻倍。
10.2 动态代理
- 动态代理和静态代理角色一样
- 动态代理类是动态生成的,不是我们直接写好的
- 动态代理分为 2 大类;基于接口的动态代理,基于类的动态代理
- 基于接口——JDK 的动态代理【这里使用】
- 基于类:cglib
- java 字节码实现 JAVAssist
需要了解两个类:Proxy(代理类), InvocationHandle(调用处理程序)
InvocationHandle 是一个接口
//实现代理接口,动态生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
//代理接口
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成代理对象
/**
* 参数含义:
* 代理的类加载器,加载类在什么位置
* 真实角色和代理角色需要实现那个接口
* InvocationHandler 这里就是 this
* @return
*/
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 methodName){
System.out.println("执行了"+methodName+"方法");
}
}
测试
//已静态代理的租房案例测试
public class Client {
public static void main(String[] args) {
//真实角色
Host host = new Host();
//代理角色
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//通过调用程序来处理我们要调用的接口对象(必须是接口),让代理角色实现真实角色实现的接口
pih.setTarget(host);
//创建代理类
Rent proxy =(Rent) pih.getProxy();
//调用方法
proxy.rent();
}
}
- 可以使真实角色操作更加纯粹,不用关注公共业务
- 公共也交给代理角色!实现了业务分工,耦合性降低
- 公共业务发生扩展时候,方便集中管理
- 一个动态代理类代理一个接口,一般就是对应一类业务
- 一个动态代理类可以代理多个类,只要实现同一个接口即可
11 AOP
11.1什么是AOP
AOP:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP 是 OOP 的延续,是软件开发中的一个热点,也是 spring 框架的一个重要内容,是函数式编程的一种衍生泛型。利用 aop 可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高开发效率。
- 实际应用:比如之前我们的功能是增删改查,此时需要增加一些功能比如说日志,前置通知后置通知等,在不改变原业务基础上,就可以用 aop 实现,这就类似与动态代理。
11.2 AOP 在 Spring 中作用
提供声明式事务:允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能,即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等
- 切面(Aspect):横切关注点 被模块化的特殊对象,即,**它是一个类 ** 类似上述动态代理中的 Log,可以是我们自定义的类做切面
- 通知(Advice):切面必须要完成的工作。即,**它是类中的一个方法 ** Log 中的方法 切面中方法在什么时候执行
- 目标(Target):被通知对象 接口或方法
- 代理(Proxy):向目标对象应用通知之后创建的对象 代理类
- 切入点(PointCut):切面通知执行的“地点”的定义 在哪里执行
- 连接点(JointPoint):与切入点匹配的执行点 在哪里执行
11.3 使用 Spring 实现 AOP
业务类
public interface UserService {
void add();
void delete();
void update();
void select();
}
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("添加用户");
}
@Override
public void delete() {
System.out.println("删除用户");
}
@Override
public void update() {
System.out.println("更新用户");
}
@Override
public void select() {
System.out.println("查询用户");
}
}
方式一:使用 Spring 接口实现 AOP
- 定义类
public class Log implements MethodBeforeAdvice {
/**
*
* @param method 要执行的目标对象的方法
* @param objects 参数
* @param o 目标对象
* @throws Throwable
*/
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
//执行后
public class AfterLog implements AfterReturningAdvice {
//返回值
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"返回结果为"+returnValue);
}
}
- 注册到 ioc 容器和 AOP【主要 springAPI 接口实现】
<!-- 方式一使用原生 APi 接口-->
<!-- 配置 aop 需要导入 aop 约束-->
<aop:config>
<!-- 配置切入点,需要在哪里执行-->
<aop:pointcut id="pointCut" expression="execution(* com.study.service.UserServiceImpl.*(..))"/>
<!-- 通知在哪里执行-->
<aop:advisor advice-ref="beforeLog" pointcut-ref="pointCut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointCut"/>
</aop:config>
- 测试
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理代理的是接口
UserService userService =(UserService) context.getBean("userService");
userService.delete();
}
}
方式二:自定义通知类来实现【主要是自定义切面】
- 自定义切面
//自定义类
public class DiyPointCut {
public void before(){
System.out.println("方法执行前");
}
public void after(){
System.out.println("方法执行后");
}
}
- 配置 bean 和切面
<!-- 注册 bean-->
<bean id="userService" class="com.study.service.UserServiceImpl"/>
<!--自定义类-->
<bean id="diy" class="com.study.DiyPointCut"/>
<aop:config>
<!-- 切面,需要引用我们自定义的类作为切面-->
<aop:aspect ref="diy">
<!-- 切入点-->
<aop:pointcut id="pointCut" expression="execution(* com.study.service.UserServiceImpl.*(..))"/>
<!-- 通知-->
<aop:after method="after" pointcut-ref="pointCut"/>
<aop:before method="before" pointcut-ref="pointCut"/>
</aop:aspect>
</aop:config>
方式三:使用注解实现
- 使用注解自定义切面类
@Aspect//标注这个类是一个切面
public class AnnotationPointCut {
//切入点
@Before("execution(* com.study.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("====方法执行前===");
}
@After("execution(* com.study.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("===方法执行后===");
}
//在环绕增强中,我们可以给定一个参数,代表我们要处理切入的点
@Around("execution(* com.study.service.UserServiceImpl.*(..))")
//连接点(JointPoint):与切入点匹配的执行点
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
//执行方法,只有调用方法 才会执行,没有执行则====方法执行前===不会输出
Object proceed = jp.proceed();
System.out.println("环绕后");
}
}
/**
* 输出顺序
* 环绕前
* ====方法执行前===
* 删除用户
* 环绕后
* ===方法执行后===
*/
- 配置 xml
<!-- 方式三 注解方式-->
<context:component-scan base-package="com.study"/>
<bean id="annotation" class="com.study.AnnotationPointCut"/>
<!-- 开启切面注解支持 代理模式默认基于接口 jdk(proxy-target-class="false"),
基于类cglib(proxy-target-class="true")-->
<aop:aspectj-autoproxy/>
<aop:aspectj-autoproxy proxy-target-class="false"/>
- 测试
12 整合 Mybatis
步骤:
导入 依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</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.2.12.RELEASE</version>
</dependency>
<!-- spring操作数据库 jdbc 需要的包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
</dependencies>
用到的类
- pojo
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
- mapper 类和 xml文件
public interface UserMapper {
List<User> selectUsers();
//添加用户
int addUser(User user);
//删除用户
int delete(@Param("id") int id);
}
<?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.study.mapper.UserMapper">
<select id="selectUsers" resultType="user">
select * from USER
</select>
<insert id="addUser" parameterType="user">
insert into user(id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
<delete id="delete" parameterType="int" >
delete from user where id =#{id}
</delete>
</mapper>
- 业务实现类
//我们所有操作,都使用 sqlSessionTemplate等同于之前的sqlSession
public class ServiceImpl implements UserMapper {
private SqlSessionTemplate sqlSession;
public ServiceImpl(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List<User> selectUsers() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.selectUsers();
return users;
}
@Override
public int addUser(User user) {
return 0;
}
@Override
public int delete(int id) {
return 0;
}
}
编写配置文件
- mybatis 配置文件(原来的获取 selSession 通过 spring 进行依赖注入,这里用于配置一些设置)
<?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.study.pojo"/>
</typeAliases>
</configuration>
- spring 配置文件(用于放置固定的 bean 对象)
<?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" xmlns:tx="http://www.springframework.org/schema/tx"
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/tx https://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 固定的 mybatis 模板-->
<!-- 使用 spring 的数据源代替 mybatis-->
<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"/>
<property name="username" value="root"/>
<property name="password" value="rootroot"/>
</bean>
<!-- 配置 SqlSessionFactoryBean-->
<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/study/mapper/*.xml"/>
</bean>
<!-- 配置 sqlSession 使用 sqlsessionTemplate 需要注入,用继承SqlSessionDaoSupport就无需配置-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 由于SqlSessionTemplate没有 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">
<!-- 给那些方法配置事务
配置事务传播特性-->
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务切入-->
<aop:config>
<aop:pointcut id="pointCut" expression="execution(* com.study.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/>
</aop:config>
- applicationContext.xml (将所有配置文件导入到该配置类下,这个类主要做动态 bean 的管理)
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-dao.xml"/>
<!-- 这个文件用于管理添加的 bean 对象,我使用的是构造器注入,使用 sqlsessionTemplate 需要注入-->
<bean id="userService" class="com.study.service.ServiceImpl" c:sqlSession-ref="sqlSession"/>
</beans>
测试
public class MyTest {
@Test
public void userTest() throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userService = context.getBean("userService", UserMapper.class);
List<User> users = userService.selectUsers();
for (User user : users) {
System.out.println(user);
}
}
}
在上述的实现中, spring 整合 mybatis 中提供了 SqlSessionTemplate 来获得 mapper 完成查询,为了能使用SqlSessionTemplate,因此需要在xml 注入对象。
实现配置文件和方法和上面相同
除此我们可以让实现类中继承SqlSessionDaoSupport,那我们就无需注入SqlSessionTemplate,直接通过sqlSessionFactor就能获得
<!--其余配置和之前一样,无需再配置文件中注入 SqlSession,只注入sqlSessionFactory即可-->
<bean id="userService2" class="com.study.service.ServiceImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
public class ServiceImpl2 extends SqlSessionDaoSupport implements UserMapper {
@Override
public List<User> selectUsers() {
SqlSession sqlSession = getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.selectUsers();
User user = new User(7, "zhangsan", "119911");
mapper.addUser(user);
mapper.delete(1);
return users;
}
@Override
public int addUser(User user) {
return getSqlSession().getMapper(UserMapper.class).addUser(user);
}
@Override
public int delete(int id) {
return getSqlSession().getMapper(UserMapper.class).delete(1);
}
}
13. 声明式事务
具体实现方法同上
13.1 回顾事务
- 要么成功,要么失败
- 事务在项目中很重要,涉及数据的一致性问题
- 确保完整性和一致性
事务的 ACID 原则
- 原子性 确保都成功都失败
- 一致性 要么都提交,要么都失败
- 隔离性 多个业务可能操作同一个资源是互相隔离的,防止数据损坏
- 持久性 事务一旦提交,无论系统发生什么问题,结果都不会被影响,被持久化的写到存储器中
13.2 spring中的事务
- 声明式事务:AOP,不改变原有代码
- 编程式事务:需要改变原有代码
思考:
为什么需要事务?
- 如果不配置事务,可能存在数据提交不一致情况下;
- 如果不在 spring 中去配置声明事务,我们就需要在代码中手动配置事务
- 事务在开发中很重要,涉及数据完整性和一致性