1、Spring学习笔记
1.1,简介
-
2002年首次推出了Spring框架的雏形:interface21框架
-
以interface21位基础,于2004年3月24号正式发布了1.0正式版
-
Rod Johnson Spring Framework 创始人
-
理念:简化服务器的开发,使现有的技术更加容易使用,本身就是一个大杂烩,整合了现有的技术框架
-
SSH:Struct2 + Spring + Hibernate
-
SSM: SpringMvc + Spring + MyBatis
官方下载地址:https://repo.spring.io/libs-release-local/org/springframework/spring/
Maven地址:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
1.2,优点
- Spring是一个免费的开源的框架(容器)
- Spring是一个轻量级的,非入侵式的框架
- 控制反转(IOC),面向切面编程(AOP) 【重点】
- 支持事物的处理,对框架整合的支持
总结:Spring就是一个轻量级的控制反转(IOC),和面向切面(AOP)的编程的框架
1.3,组成
1.4,拓展
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HXCRh73h-1624611093030)(C:\Users\刘子祥\AppData\Roaming\Typora\typora-user-images\image-20210618145848483.png)]
Spring Boot:
- 一个快速开发的脚手架
- 基于SpringBoot可以快速的开发微服务
- 约定大于配置
Spring Cloud:
- Spring Cloud 基于Spring Boot实现的
现在大部分公司都在使用Spring Boot 进行快速开发,学习Spring Boot 的前提,需要完全掌握Spring以及Spring MVC
弊端:发展了太久之后,违背了原来的理念,配置十分繁琐(后期)配置地狱
2、IOC理论推导
在之前的业务中,用户的需求可能会影响到我们原来的代码,我们需要根据用户的需求去修改原代码,如果程序代码量十分大,修改一次的成本十分昂贵
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Cv3rE124-1624611093032)(C:\Users\刘子祥\AppData\Roaming\Typora\typora-user-images\image-20210621094721455.png)]
使用set接口实现,革命性的变化
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ee1CPvjt-1624611093033)(C:\Users\刘子祥\AppData\Roaming\Typora\typora-user-images\image-20210621094737057.png)]
private UserDao userdao;
//利用set实现动态的值的注入
public void setUserDao(UserDao userdao){
this.userdao=dao;
}
- 之前,程序是主动创建对象,控制权在程序员手上!
- 使用了set注入后,程序不再具有主动性,而是变成了被动的接受对象!
这种思想,从本质上解决了问题,我们程序员不用再去管理对象的创建了,系统的耦合性大大降低,可以更加专注的早业务的实现上。这是IOC的原型
2,1.IOC本质
**控制反转是一种设计思想(Inversion of Control)DI(依赖注入)是实现IOC的一种方法,**也有人认为DI只是IOC的另一种说法,
没有IOC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,
控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得对象的依赖关系反转了
控制反转是一种通过描述(XML或者注解),并通过第三方生产或获取特定对象的方式,在Spring中实现控制反转的是IOC容器,其实现方法是依赖注入(Dependency Injection DI)
中文文档:https://www.docs4dev.com/docs/zh/spring-framework/5.1.3.RELEASE/reference
2,2.HelloSpring
-
配置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"> <!--使用Spring来创建对象,在Spring中这些都称为Bean 类型 变量名 = new 类型() Hello hello = new Hello id=变量名 class=需要 new 的类型或对象 property=给对象中的属性赋值 --> <bean id="hello" class="com.liu.entity.Hello"> <property name="str" value="123"/> </bean> </beans>
-
-
测试
-
public static void main(String[] args) { //**ApplicationContext context = new ClassPathXmlApplicationContext("配置好的Beans.xml,可配置多个");** ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Hello hello = (Hello) context.getBean("hello"); System.out.println(hello.toString()); }
-
实例化容器
ApplicationContext context = new ClassPathXmlApplicationContext(“配置好的Beans.xml,可配置多个”);
总结:到了现在,我们彻底不用再去程序中去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的IOC
一句话搞定:对象由Spring来创建,管理,装配
2,3.IOC创建对象的方式
-
使用无参构造创建对象,默认!
-
假如使用有参构造创建对象
-
下标赋值
-
<!--根据下标--> <bean id="hello" class="com.liu.entity.Hello"> <constructor-arg index="0" value="翠花"/> </bean>
-
类型
-
<!--根据类型创建,不建议使用--> <bean id="hello" class="com.liu.entity.Hello"> <constructor-arg type="java.lang.String" value="狂神"/> </bean>
-
根据参数
-
<!--根据参数名--> <bean id="hello" class="com.liu.entity.Hello"> <constructor-arg name="str" value="Java"/> </bean>
-
总结:在配置文件加载的时候,会将xml容器中管理的所有对象全部初始化!
3,Spring配置
3,1.别名(alias)
<!--别名,如果添加了别名,我们也可以使用别名来获取到这个对象-->
<alias name="hello" alias="kk"/>
3,2.Bean的配置
<!--
id:bean的唯一标识符,相当于变量名
class:bean对象所对应的全限定名,包名加类型
name:也是别名,而且name可以同时取多个别名
-->
<bean id="helloT" class="com.liu.entity.HelloT" name="uu,bb">
3,3.import导入
一般用于团队开发,他可以将多个配置文件,导入合并为一个总的配置文件
<import resource="beans.xml"/>
这样使用的时候就只需要调用总的配置文件就行了
4、依赖注入
4,1.构造器注入
就是带参构造注入
4,2.set方式注入【重点】
- 依赖注入:set注入
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器来注入
4,3.环境搭建
-
复杂类型
public class Address { private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
2.真实测试对象
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> bobbys;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info;
}
3.配置文件
<?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="add" class="com.liu.entity.Address">
<property name="address" value="地球"/>
</bean>
<bean id="student" class="com.liu.entity.Student">
<!--第一种,普通值注入,直接value赋值-->
<property name="name" value="狂神"/>
<!--Bean注入,ref-->
<property name="address" ref="add"/>
<!--数组注入-->
<property name="books">
<array>
<value>西游记</value>
<value>水浒传</value>
<value>三国演义</value>
</array>
</property>
<!--list注入-->
<property name="bobbys">
<list>
<value>看书</value>
<value>听歌</value>
<value>看电影</value>
</list>
</property>
<!--map注入-->
<property name="card">
<map>
<entry key="身份证" value="111111222233334444"></entry>
<entry key="银行卡" value="1221232355664444000"></entry>
</map>
</property>
<!--set注入-->
<property name="games">
<set>
<value>LOL</value>
<value>CSGO</value>
<value>GTA5</value>
</set>
</property>
<!-- null值-->
<property name="wife">
<null/>
</property>
<!--Properties注入-->
<property name="info">
<props>
<prop key="学号">2021-06-21</prop>
<prop key="性别">男</prop>
</props>
</property>
</bean>
</beans>
4.测试
public static void main(String[] args) {
ApplicationContext context =new ClassPathXmlApplicationContext("ApplicationXmlContext.xml");
Student student = (Student) context.getBean("student");
System.out.println(student);
}
//结果
//Student{name='狂神', address=Address{address='地球'}, books=[西游记, 水浒传, 三国演义], bobbys=[看书, 听歌, 看电影],
// card={身份证=111111222233334444, 银行卡=1221232355664444000}, games=[LOL, CSGO, GTA5], wife='null', info={学号=20210621, 性别=男}}
4,4.拓展方式注入(C,P)
P命名空间
<!--在配置文件头部导入链接-->
xmlns:p="http://www.springframework.org/schema/p"
<!--p命名空间注入,可以直接注入属性的值,类似于 property -->
<bean id="user" class="com.liu.entity.User" p:name="哈哈" p:age="16"/>
c命名空间
<!--在配置文件头部导入链接-->
xmlns:c="http://www.springframework.org/schema/c"
<!--c命名空间注入,通过构造器(有参)注入,类似于 constructor-arg -->
<bean id="user2" class="com.liu.entity.User" c:age="13" c:name="狂神"/>
注意:p命名空间和c命名空间不能直接使用,需要导入约束!
4,5.bean的作用域
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TLTWUUWT-1624611093037)(C:\Users\刘子祥\AppData\Roaming\Typora\typora-user-images\image-20210622100411936.png)]
-
单例模式(Spring默认模式)
-
<bean id="user" class="com.liu.entity.User" p:name="哈哈" p:age="16" scope="singleton"/>
-
-
原型模式:每次从容器中取出(get)时,都会产生一个新对象
-
<bean id="user" class="com.liu.entity.User" p:name="哈哈" p:age="16" scope="prototype"/>
-
-
其余的request,session,application,这些只能在web开发中用到!
5、Bean的自动装配
- 自动装配是Spring满足Bean依赖的一种方式
- Spring会在上下文中自动寻找,并自动给Bean装配属性
在Spring中,有三种装配的方式
- 在xml中显示的配置
- 在java中显示配置
- 隐式的自动装配bean【重点】
5,1.ByName自动装配
<bean id="dog" class="com.liu.entity.Dog"/>
<bean id="cat" class="com.liu.entity.Cat"/>
<!-- byName: 会在容器上下文中查找,和自己对象set方法后面的值对应的 beanId -->
<bean id="people" class="com.liu.entity.People" autowire="byName">
<property name="name" value="狂神"/>
</bean>
5,2.ByType自动装配
<bean id="dog" class="com.liu.entity.Dog"/>
<bean id="cat" class="com.liu.entity.Cat"/>
<!-- byType: 会在容器上下文中查找,和自己对象属性类型相同的bean (匹配class) 全局唯一 -->
<bean id="people" class="com.liu.entity.People" autowire="byType">
<property name="name" value="狂神"/>
</bean>
小结:
- byName:需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的一致
- byType:需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致
5,2.使用注解自动装配
注解:
-
导入约束 :
-
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/beans/spring-context.xsd"> <bean id="dog2" class="com.liu.entity.Dog"/> <bean id="dog1" class="com.liu.entity.Dog"/> <bean id="cat2" class="com.liu.entity.Cat"/> <bean id="cat1" class="com.liu.entity.Cat"/> </beans>
-
-
配置注解的支持,开启注解:
<!--开启注解--> <context:annotation-config/>
-
使用 @Autowired(Spring 注解)
-
再实体类进行注解,可以写在属性上方,或者属性的set方法上方,注意,字段名一定要和bean的id名一致,否则就会报空指针异常
-
如果显示的定义了Autowired的required属性为false,就说明这个对象可以为null
-
@Nullable 字段标记了这个注解,说明这个字段可以为空
-
@Autowired @Qualifier(value = "cat1") private Cat cat; @Autowired @Qualifier(value = "dog2") private Dog dog; public People(@Nullable String name) { this.name = name; }
-
如果Autowired自动装配的环境比较复杂的时候,有多个对象,自动装配无法通过一个注解【Autowired】完成的时候,我们可以使用@Qualifier(value = “beanid”)去配置Autowired使用,指定一个唯一的Bean注入对象
-
-
拓展:@Resource(java注解)
-
@Resource(name = “beanid”)在配置环境复杂的时候,也可以去指定一个唯一的Bean注入对象,等同于@Qualifier(value = “beanid”),不过@Resource使用较少
-
@Resource @Resource(name = "cat1") private Cat cat; @Resource(name = "dog1") @Resource private Dog dog;
-
-
@Resource与@Autowired区别
- 都是用来自动装配的,都可以放在属性字段上
- @Autowired 是通过byType的方式实现,而且必须要求这个对象存在,否则报错
- @Resource 默认通过byName方式实现,如果找不到名字,则通过byType方式实现,都找不到,则报错
- 执行顺序不同:@Autowired通过byType实现,@Resource默认使用byName方式实现
6、使用注解开发
-
导入约束,开启注解支持
-
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/beans/spring-context.xsd"> <!--指定要扫描的包,这个报下的注解就会生效--> <context:component-scan base-package="com.liu.entity"/> <context:annotation-config/> </beans>
-
-
@Component 注解
-
@Component:组件,放在类上,说明这个类被Spring管理了,就是Bean,不用再去xml文件配置!
-
//等同于<bean id="user" class="com.liu.entity.User"/> @Component public class User { public String name="狂神"; }
-
-
属性注解@Value
-
可以放在属性上或者属性的set方法上
-
//等同于:<property name="name" value="翠花"/> @Value("翠花") public String name;
-
-
衍生的注解
-
@Component 有几个衍生的注解,在web开发中,会按照MVC三层架构分层
dao :【@Repository】
service :【@Service】
controller :【@Controller】
这四个注解功能都是一样的,都是代表将某个类注册到Spring容器中,然后装配Bean
-
-
作用域 @Scope
-
@Scope("singleton")
-
-
小结 :
xml与注解
- xml更加万能,适用于任何场合,维护简单方便
- 注解不是直接类使用不了,维护相对复杂
xml与注解最佳实践
- xml用来管理bean
- 注解只负责属性的注入
- 在使用的过程中,只需要注意一个问题,必须让注解生效,就需要开启注解的支持
7、使用java的方式配置Spring
-
实体类
@Component public class User { private String naem; public String getNaem() { return naem; } @Value("翠花") public void setNaem(String naem) { this.naem = naem; } @Override public String toString() { return "User{" + "naem='" + naem + '\'' + '}'; } }
-
appConfig配置类
//这个也会被Spring容器接管,注册到容器中,因为他本身就是一个@Component //@Configuration代表这是一个配置类,等同行与之前的beans.xml //@ComponentScan 指定要扫描的包,这个包下的注解就会生效 //@ComponentScan 等同于<context:component-scan base-package="com.liu.entity"/> //@Import 引入别的配置类 @Configuration @ComponentScan("com.liu") @Import(UserConfig2.class) public class UserConfig { // 注册一个bean,等同于之前的bean标签 //方法的名字相当于bean标签中的id //这个方法中返回值相当于bean标签中的class @Bean public User getUser(){ //返回要注入到bean的对象 return new User(); } }
-
测试类
@Test public void test(){ //如果完全使用了配置类,我们只能通过 AnnotationConfig 上下文来获取容器,配置class类进行加载 ApplicationContext context = new AnnotationConfigApplicationContext(UserConfig.class); User getUser = (User) context.getBean("getUser"); System.out.println(getUser); }
小结:
这种纯java的配置方式,在SpringBoot中随处可见
8、代理模式
代理模式:SpringAOP的底层 面试必问【SpringAOP SpringMVC】
代理模式的分类:
- 静态代理
- 动态代理
- [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-akZVqfVR-1624611093039)(C:\Users\刘子祥\AppData\Roaming\Typora\typora-user-images\image-20210623100612577.png)]
8.1、静态代理
角色分析:
- 抽象角色:一般会使用接口或者抽象类来解决 (房源)
- 真实角色:被代理的角色 (房东)
- 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作 (寻找房源之类)
- 客户:访问代理对象的人 (有租房需求的人)
测试:
-
接口
-
// 抽象角色 房源 public interface Rent { public void rent(); }
-
-
真实角色
-
//真实角色 房东 public class Host implements Rent { public void rent() { System.out.println("我有房子要出租!"); } }
-
-
代理角色
-
//代理角色 中介代理房东租房 public class Proxy implements Rent { private Host host; public Proxy(Host host) { this.host = host; } public Proxy() { } public void rent() { seeHouse(); host.rent(); hetong(); setMoney(); } //看房 public void seeHouse(){ System.out.println("中介带你看房!"); } //合同 public void hetong(){ System.out.println("签订租房合同!"); } //收取中介费 public void setMoney(){ System.out.println("收取中介费!"); } }
-
-
客户
-
// 客户 有租房需求的人 public class Client { public static void main(String[] args) { //房东要租房子 Host host = new Host(); //代理角色:中介,帮房东出租房子,同时还会有一些附属操作 Proxy p = new Proxy(host); p.rent(); } }
-
代理模式的好处:
- 可以使真实角色的操作更纯粹,不用去关注一些公共的业务
- 公共业务交给代理角色!实现了业务的分工
- 公共业务发生扩展的时候,方便集中管理
缺点:
- 一个真实角色,就会产生一个代理角色,代码量会翻倍,开发效率变低
8.2、动态代理
- 动态代理个静态代理角色一样
- 动态代理的代理类是动态生成的,不是我们直接写好的!
- 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
- 基于接口:JDK动态代理
- 基于类:cglib
- java字节码实现:javasist
两个类 Proxy 代理 InvocationHandler 调用处理程序
- Proxy:提供创建动态代理和实例的静态方法
- InvocationHandler :处理代理实例,并返回结果
动态代理的好处
- 可以使真实角色的操作更纯粹,不用去关注一些公共的业务
- 公共业务交给代理角色!实现了业务的分工
- 公共业务发生扩展的时候,方便集中管理
- 一个动态代理类代理的是一个接口一般就是对应的一类业务
- 一个动态代理类,可以代理多个类,只要是实现了同一个接口即可
实现动态代理:ProxyInvocationHandler工具类
//用这个类,自动生成代理类
// InvocationHandler 实现接口
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的借口
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成得到代理类
// getClassLoader()类加载器
//target.getClass().getInterfaces() 得到被代理的接口
// Proxy 提供创建动态代理和实例的静态方法
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
// InvocationHandler 处理代理实例,并返回结果
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+"方法");
}
}
测试:
public static void main(String[] args) {
//真实角色
UserServlet service = new UserServlet();
//代理角色【暂无】
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//设置要代理的对象
pih.setTarget(service);
//动态生成代理类
UserService proxy = (UserService) pih.getProxy();
//执行方法
proxy.add();
}
9、AOP
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-d4pY1ZTF-1624611093040)(C:\Users\刘子祥\AppData\Roaming\Typora\typora-user-images\image-20210623161223851.png)]
9.1、什么是AOP
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
9.2、AOP在Spring中的作用
提供声明式事务;允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 …
- 切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。
- 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
- 目标(Target):被通知对象。
- 代理(Proxy):向目标对象应用通知之后创建的对象。
- 切入点(PointCut):切面通知 执行的 “地点”的定义。
- 连接点(JointPoint):与切入点匹配的执行点。
9.3、使用Spring实现AOP
使用AOP织入,需要导入一个依赖包【重点】
<!--AOP--> <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.6</version> </dependency>
方式一:使用Spring的API接口
-
准备工作
-
public interface BookService { void add(); void del(); void upd(); void sel(); }
-
public class BookServiceImpl implements BookService { public void add() { System.out.println("添加书本"); } public void del() { System.out.println("删除书本"); } public void upd() { System.out.println("修改书本"); } public void sel() { System.out.println("查询书本"); } }
-
-
要切入的内容
-
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); } }
-
public class Log implements MethodBeforeAdvice { //Method 要执行的目标对象的方法 //args 参数 //target 目标对象 public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println(target.getClass().getName()+"的"+method.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" 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="bookService" class="com.liu.entity.BookServiceImpl"/> <bean id="log" class="com.liu.log.Log"/> <bean id="afterLog" class="com.liu.log.AfterLog"/> <!--在头文件导入Aop约束 方式一:使用原生的Spring API接口--> <aop:config> <!--切入点 expression:表达式 expression(要执行的位置):--> <aop:pointcut id="pointcut" expression="execution(* com.liu.entity.BookServiceImpl.* (..))"/> <!--执行环绕增加--> <aop:advisor advice-ref="log" pointcut-ref="pointcut"/> <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/> </aop:config> </beans>
-
-
测试
-
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml"); //动态代理的是接口,要注意 BookService bookService = context.getBean("bookService", BookService.class); bookService.add(); }
-
方式二:使用自定义类实现AOP【切面定义】
-
自定义类
-
public class DiyPointcut { public void before(){ System.out.println("====方法执行前===="); } public void after(){ System.out.println("====方法执行后===="); } }
-
-
配置文件编写
-
<?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="bookService" class="com.liu.entity.BookServiceImpl"/> <bean id="log" class="com.liu.log.Log"/> <bean id="afterLog" class="com.liu.log.AfterLog"/> <!--在头文件导入Aop约束--> <!--方式二:自定义类--> <bean id="diy" class="com.liu.diy.DiyPointcut"/> <aop:config> <!--自定义切面 ref 要引用的类--> <aop:aspect ref="diy"> <!--要切入的点--> <aop:pointcut id="point" expression="execution(* com.liu.entity.BookServiceImpl.*(..))"/> <aop:before method="before" pointcut-ref="point"/> <aop:after method="after" pointcut-ref="point"/> </aop:aspect> </aop:config> </beans>
-
-
测试
-
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml"); //动态代理的是接口,要注意 BookService bookService = context.getBean("bookService", BookService.class); bookService.add(); }
-
方式三:使用注解实现AOP
-
@Aspect//标注这个是一个切面 public class AnnotationPointCut { @Before("execution(* com.liu.entity.BookServiceImpl.*(..))") public void before(){ System.out.println("前"); } @After("execution(* com.liu.entity.BookServiceImpl.*(..))") public void after(){ System.out.println("后"); } //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点 @Around("execution(* com.liu.entity.BookServiceImpl.*(..))") public void around(){ }
-
<?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="bookService" class="com.liu.entity.BookServiceImpl"/> <bean id="log" class="com.liu.log.Log"/> <bean id="afterLog" class="com.liu.log.AfterLog"/> <bean id="annotationPointCut" class="com.liu.diy.AnnotationPointCut"/> <!--开启注解支持--> <aop:aspectj-autoproxy/> </beans>
10、整合MyBatis
步骤:
-
导入jar包
-
Junit
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--Lombok--> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </dependency>
-
MyBatis
<!--MyBatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency>
-
MySQL数据库
<!--连接数据库--> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency>
-
Spring相关的
<!--spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.8</version> </dependency> <!--Spring操作数据库,还需要一个 spring-jdbc包--> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.8</version> </dependency>
-
aop织入
<!--AOP--> <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.6</version> </dependency>
-
mybatis-spring【】
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency>
-
-
编写配置文件
-
测试s
10.1、MyBatis-Spring
-
编写数据源配置
-
<!--DataSource : 使用Spring的数据源替换MyBatis的配置 我们这里使用spring提供的JDBC --> <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?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="123"/> </bean>
-
-
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/liu/mapper/*.xml"/> </bean>
-
-
sqlSessionTemplate
-
<!--SqlSessionTemplate:就是我们使用的sqlSession --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!--只能使用构造器注入--> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean>
-
-
需要给接口加上实现类
-
public class UserMapperImpl implements UserMapper { //原来我们所有的操作,都是用sqlSession来执行,现在是SqlSessionTemplate private SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } public List<User> query() { UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.query(); } }
-
-
将自己写的实现类,注入到Spring中
-
<import resource="applicationcontext.xml"/> <bean id="userMapper" class="com.liu.mapper.UserMapperImpl"> <property name="sqlSession" ref="sqlSession"/> </bean>
-
-
测试
-
public void test() throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); UserMapper user= context.getBean("userMapper", UserMapper.class); for (User user1 : user.query()) { System.out.println(user1); } }
-
11、声明式事务
11.1、回顾事务
- 要么都成功,要么都失败
- 事务在项目开发中,十分重要,涉及到数据的一致性问题,不能马虎
- 确保完整性和一致性
11.2、Spring中的事务管理
-
声明式事务:AOP【推荐】
-
在Spring配置文件中配置事务
<!-- 配置声明式事务 --> <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 REQUIRED:Spring默认事务,如当前不存在事务,则新建--> <tx:attributes> <tx:method name="ad" propagation="REQUIRED"/> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!--配置事务切入--> <aop:config> <aop:pointcut id="txPointCut" expression="execution(* com.liu.mapper.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config>
-
-
编程式事务:需要在代码中,进行事物的管理 【不建议使用】
为什么需要事务?
- 如果不配置事务,会出现数据提交不一致的情况
- 如果我们不在Spring中去配置声明式事务,我们就需要在代码中手动配置事务
- 事务在项目的开发中,十分重要,涉及到数据的一致性和完整性的问题,不容马虎