Spring
常用信息
常用依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
注解说明
- @Autowired : 自动装配通过类型、名字
如果Autowired不能自动装配上属性,则使用@Qualifier(value=“beanID”)进行选择
- @Nullable : 字段可以为null
- @Resource : 自动装配通过名字、类型
- @Component : 组件,放在类上,说明这个类被Spring管理了,就是bean!
简介
介绍
-
Spring:春天—>软件行业的春天
-
2002,首次退出Spring框架的雏形:interface21框架
-
2004年3月24日,Spring框架即以interface21框架为基础,经过重新设计,并不断丰富其内涵,发布了1.0正式版
-
Rod Johnson,Spring Framework创始人(悉尼大学音乐学博士)
-
spring理念:使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架
-
SSH:Struct2 + Spring + Hibernate
-
SSM:SpringMVC + Spring + MyBatis
官网:https://spring.io/projects/spring-framework#overview
源码:https://github.com/spring-projects/spring-framework
依赖:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.9</version>
</dependency>
优点
- Spring 是一个开源的免费的框架(容器)
- Spring 是一个轻量级、非入侵式的框架
- 控制反转(IOC),面向切面编程(AOP)
- 支持事务的处理,对框架整合的支持
总结:Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架
组成

拓展
现代化的Java开发就是基于Spring的开发
- Spring Boot
- 一个快速开发的脚手架
- 基于SpringBoot可以快速开发单个微服务
- 约定大于配置
- Spring Cloud
- SpringCloud基于SpringBoot实现的
因为现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC!承上启下的作用。
弊端:发展了太久之后,违背了原来的理念!配置十分繁琐,人称:“配置地域!”
IOC
-
UserDao接口
public interface UserDao { void getUser(); } -
UserDaoImpl实现类
public class UserDaoMysqlImpl implements UserDao{ @Override public void getUser() { System.out.println("Mysql获取用户数据"); } }public class UserDaoOracleImpl implements UserDao{ @Override public void getUser() { System.out.println("Oracle获取用户数据"); } } -
UserService业务接口
public interface UserService { void getUser(); } -
UserServiceImpl实现类
public class UserServiceImpl implements UserService{ private UserDao userDao;//如果没有set而是在这里设定,则定死了代码,使得变更非常麻烦 //利用set进行动态实现值的注入! public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public void getUser() { userDao.getUser(); } }
在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改源代码!如果程序代码量十分大,修改一次的成功将十分昂贵!
我们使用一个set接口实现.已经发生了革命性的变化!
private UserDao userDao;
//利用set进行动态实现值的注入!
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
- 之前,程序是主动创建对象!控制权在程序员手中。
- 使用了set注入后,程序不再具有主动性,而是变成了被动的接收对象!
这种思想,从本质上解决了问题,我们程序员不用再管理对象的创建了。系统的耦合性大大降低,可以更加专注的在业务的实现上!这是IOC的原型!

IOC本质
控制反转IOC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IOC的一种方式,也有人认为DI只是IOC的另一种说法。在没有IOC的程序中,我们使用面向对象编程,对象的创建于对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IOC容器,其实现方法是依赖注入(Dependency Injection,DI)
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
第一个Spring项目 HelloSpring
- Hello对象是谁创建的?
由Spring创建 - Hello对象的属性时怎么设置的?
由Spring容器设置的,property
这个过程就叫控制反转:
控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring手,对象是由Spring来创建的
反转:程序本身不创建对象,而编程被动的接收对象
依赖注入:就是利用set方法来进行注入的
IOC是一种编程思想,由主动的编程变成被动的接收
IOC创建对象的方式
-
使用无参构造创建对象,默认
-
假设我们要使用有参构造创建对象
<!--第一种 下标赋值--> <bean id="user" class="com.kun.pojo.User"> <constructor-arg index="0" value="小坤"/> </bean> <!--第二种 类型赋值 不建议使用--> <bean id="user2" class="com.kun.pojo.User"> <constructor-arg type="java.lang.String" value="小坤2"/> </bean> <!--第三种 直接通过参数名设置--> <bean id="user3" class="com.kun.pojo.User"> <constructor-arg name="name" value="小坤3"/> </bean>
总结:在配置文件加载的时候,容器中管理的对象就已经初始化了
Spring配置
别名 alias
<!--别名,如果添加了别名,两个名称都指向同一个引用-->
<alias name="user" alias="newUser"/>
Bean的配置
<!--
id:bean的唯一标识符(可以alias,name取别名),相当于对象名
class:bean对象所对应的全限定名:包名+类型(基本数据类型直接写类型)
name:别名,而且可以通过','或' '或';'等分隔,取多个别名
-->
<bean id="user4" class="com.kun.pojo.User" name="newUser4,u4 U4;newU4">
<property name="name" value="小坤4"/>
</bean>
import
import用于团队开发,将多个配置文件导入合并为一个。
<import resource="beans.xml"/>
<import resource="beans2.xml"/>
DI 依赖注入
构造器注入
set方式注入[重点]
- 依赖注入:set注入
- 依赖 bean对象的创建依赖于容器
- 注入 bean对象的所有属性,由容器来注入
[环境搭建]
-
复杂类型
@Data public class Address { private String address; } -
真实测试对象
@Data 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 Properties prop; private Student wife; } -
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.kun.pojo.Address"/> <bean id="student" class="com.kun.pojo.Student"> <!--第一种 普通注入 value--> <property name="name" value="小坤"/> <!--第二种 Bean注入 ref--> <property name="address" ref="address"/> <!--数组--> <property name="books"> <array> <value>红楼梦</value> <value>西游记</value> <value>水浒传</value> <value>三国演义</value> </array> </property> <!--list--> <property name="hobbies"> <list> <value>听歌</value> <value>写代码</value> <value>玩游戏</value> </list> </property> <!--map--> <property name="card"> <map> <entry key="身份证" value="430482********"/> <entry key="银行卡" value="**************"/> </map> </property> <!--set--> <property name="games"> <set> <value>LOL</value> <value>COC</value> <value>BOC</value> </set> </property> <!--null--> <property name="wife"> <null/> </property> <!--properties--> <property name="prop"> <props> <prop key="学号">2020****</prop> <prop key="性别">男</prop> <prop key="姓名">小坤</prop> </props> </property> </bean> </beans> -
测试类
@Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Student student = (Student) context.getBean("student"); System.out.println(student); }
拓展方式注入
我们可以使用p命名空间和c命名空间进行注入
xmlns:p="http://www.springframework.org/schema/p" 通过property方式
xmlns:c="http://www.springframework.org/schema/c" 通过construct-args方式
<?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-->
<bean id="user" class="com.kun.pojo.User" p:name="小坤" p:age="20"/>
<!--c命名空间注入,通过构造器注入:construct-args-->
<bean id="user2" class="com.kun.pojo.User" c:name="小坤" c:age="20"/>
</beans>
bean 的作用域
- singleton 单例模式,始终是同一个引用(默认)
- prototype 原型模式,每一次调用都是不同的引用,全新的对象
以下作用域只能在web项目中使用到
- request
- session
- application
- websocket
Bean的自动装配 [重点]
- 自动装配是Spring满足bean依赖一种方式
- Spring会在上下文自动寻找,并自动给bean装配引用属性[ref]
Spring中有三种装配方式
- 在xml中显示的配置
- 在java中显示装配
- 隐式的自动装配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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="cat" class="com.kun.pojo.Cat"/>
<bean id="dog" class="com.kun.pojo.Dog"/>
<bean id="people" class="com.kun.pojo.People">
<property name="name" value="小坤"/>
<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>
</bean>
</beans>
ByName 自动装配
需要保证所有的bean的id唯一,并且这个bean和自动注入的属性的set方法的值一致
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面值对应的beanID
-->
<bean id="people" class="com.kun.pojo.People" autowire="byName">
<property name="name" value="小坤"/>
</bean>
ByType 自动装配
需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致
<!--
byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean!
必须保证需要的类型的bean只有一个
-->
<bean id="people" class="com.kun.pojo.People" autowire="byType">
<property name="name" value="小坤"/>
</bean>
使用注解实现自动装配
jdk1.5支持的注解,Spring2.5就支持注解
The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML
要使用注解须知:
- 导入约束
- 配置注解的支持:
<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.sprinframework.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.kun"/>
</beans>
@Autowired
直接在属性上(或者set方法上)使用即可,使用了该注解甚至连set方法都可以不需要,因为是通过反射设置的。
自动装配的属性要在IOC(Spring)容器中存在!
科普:
@Nullable 在字段标记这个注解,说明该字段可以为null
//如果形式的定义了AutoWired的required属性为false,说明这个对象可以为null,否则不允许为空
public @interface Autowired{
boolean required() default true;
}
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个[@Autowired]完成的时候,我们可以使用@Qualifier(value=“beanID”)去配置@Autowired的使用,指定一个唯一的bean对象注入!
也可以通过java的注解 **@Resource(name=“beanID”)**方式指定唯一的bean对象
@Autowired 和 @Resource 区别:
- 都是用来自动装配的,都可以放在属性字段上
- @Autowired通过byType的方式实现,而且必须要求这个对象存在!有多个该类对象则需要@Qualifier()区分[常用]
- @Resource默认先通过byName方式实现,如果找不到名字,则通过byType实现!如果两个都找不到就报错![常用]
- 执行顺序不同:
使用注解开发 [重点]
在Spring4之后,要使用注解开发,必须导入spring-aop的包
使用注解需要导入context约束,增加注解的支持,–Bean的自动装配–
扫描指定包,使得其注解生效
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.kun"/><!--context:annotation-config--/>
context:annotation-config/和context:component-scan/的作用
注意:用了<context:component-scan base-package="..."/>可以直接删除<context:component-scan/>
-
bean
@Component -
属性如何注入
/*@Component组件 等价于<bean id="user" class="com.kun.pojo.User"> */ @Component @Data public class User { @Value("小坤")//等价于<property name="name" value="小坤"> private String name; } -
衍生的注解
@Component 有几个衍生注解,我们在web开发中,会按照mvc三层架构分层!- dao [@Repository]
- service [@Service]
- controller [@Controller]
这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean
-
自动装配
@Autowired -
作用域
@Component @Data @Scope("prototype") public class User { @Value("小坤")//等价于<property name="name" value="小坤"> private String name; } -
小结
xml 与 注解:- xml 更加万能,适用于任何场合!维护更加简单方便
- 注解 不是自己的类使用不了,维护相对复杂!
最佳实践:
- xml 用来管理bean
- 注解 只负责完成属性的注入
- 我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支
使用例子:
自动装配
cat
@Component
@Data
public class Cat {
public void shot(){
System.out.println("喵~");
}
}
dog
@Component
@Data
public class Dog {
public void shot(){
System.out.println("汪!");
}
}
people
@Component
@Data
@NoArgsConstructor
public class People {
private Cat cat;
private Dog dog;
private String name;
@Autowired
public People(Cat cat, Dog dog) {
this.cat = cat;
this.dog = dog;
}
}
测试类
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
People people = context.getBean("people", People.class);
System.out.println(people);
people.getCat().shot();
people.getDog().shot();
}
使用Java的方式配置Spring
我们现在要完全不使用Spring的xml配置,全权交给Java来做!
JavaConfig是Spring的一个子项目,在Spring4之后,它成为了一个核心功能!
实体类
@Component//将这个类注册到Spring容器中
@Data
@Scope("prototype")
public class User {
@Value("小坤")//属性注入值
private String name;
}
配置类
@Configuration//这个也会注册到Spring容器中,因为它本来就是一个@Component,这是一个配置类,就是一个beans.xml
@ComponentScan("com.kun")//扫描包
@Import(KunConfig2.class)//导入其他配置类
public class KunConfig {
/**
* 注册一个bean,相当于我们之前写的一个bean标签
* 方法的名字 相当于 bean 标签中的 id 属性
* @return 返回值 就相当于 bean 标签中的 class 属性
*/
@Bean
public User user(){
return new User();//就是返回要注入到bean的对象!
}
}
测试类
@Test
public void test(){
//如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载
ApplicationContext context = new AnnotationConfigApplicationContext(KunConfig.class);
User user = context.getBean("user", User.class);
System.out.println(user);
}
这种纯Java的配置方式,在SpringBoot中随处可见!
代理模式
为什么要学习代理模式?因为这就是SpringAOP的底层![SpringAOP 和 SpringMVC]
代理模式的分类:
- 静态代理
- 动态代理
静态代理
角色分析:
- 抽象角色:一般会使用接口或者抽象类来解决
- 真实角色:被代理的角色
- 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作
- 客户:访问代理对象的人
代码步骤:
-
接口
//出租房屋 public interface Rent { public void rent(); } -
真实角色
//房东 public class Host implements Rent{ @Override public void rent() { System.out.println("房东要出租房子"); } } -
代理角色
@Data @NoArgsConstructor @AllArgsConstructor public class Proxy implements Rent{ private Host host; @Override public void rent() { host.rent(); } //看房 public void seeHouse(){ System.out.println("中介带你看房"); } //签合同 public void contract(){ 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(); } }
代理模式的好处:
- 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
- 公共也就交给代理角色,实现了业务的分工
- 公共业务发生扩展的时候,方便集中管理
缺点:
- 一个真实角色就会产生一个代理角色;代码量会翻倍-开发效率会变低
动态代理
- 动态代理和静态代理角色一样
- 动态代理的代理类是动态生成的,不是我们直接写好的!
- 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
- 基于接口–JDK动态代理[我们在这里使用]
- 基于类:cglib
- java字节码实现:javasisit
需要了解两个类:Proxy[代理],InvocationHandler[调用处理程序]
//自动生成代理类
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+"方法");
}
}
动态代理的好处:
- 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
- 公共也就交给代理角色,实现了业务的分工
- 公共业务发生扩展的时候,方便集中管理
- 一个动态代理类代理的是一个接口,一般就是对应的一类业务
- 一个动态代理类可以代理多个类,只要是实现了同一个接口即可!
AOP
什么是AOP?
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的同意维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也就是Spring框架中的一个重要内容,是函数式编程的一种衍生类型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合性降低,提高程序的可重用性,同时提高了开发效率。
AOP在Spring中的作用
提供声明式事务;允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能。与我们业务逻辑无关的,但是我们需要关注的部分就是横切关注点。如日志,安全,缓存,事务等等…
- 切面(Aspect):横切关注点 被模块化 的特殊对象。它是一个类
- 通知(Advice):切面必须完成的工作。它是类中的一个方法
- 目标(Target):被通知对象
- 代理(Proxy):向目标对象应用通知后创建的对象
- 切入点(PointCut):切面通知 执行的“地点”的定义
- 连接点(JointPoint):与切入点匹配的执行点

AOP在不改变原有代码的情况下,增加新的功能。
使用Spring实现AOP
[重点]使用AOP需要导入的依赖包
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
<scope>runtime</scope>
</dependency>
方法一:使用Spring的API接口
切入点类(切面)日志类
public class Log implements MethodBeforeAdvice {
/**
*
* @param method 要执行的目标对象的方法
* @param args 参数
* @param target 目标对象
* @throws Throwable
*/
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
public class AfterLog implements AfterReturningAdvice {
//returnValue 返回值
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回结果为:"+returnValue);
}
}
配置文件 (excution表达式)
<?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.kun.service.UserServiceImpl"/>
<bean id="log" class="com.kun.log.Log"/>
<bean id="afterLog" class="com.kun.log.AfterLog"/>
<!--方式一:使用原生Spring API接口-->
<!--配置AOP 需要导入AOP配置-->
<aop:config>
<!--切入点:expression:表达式,execution(要执行的位置*****)-->
<aop:pointcut id="pointcut" expression="execution(* com.kun.service.UserServiceImpl.*(..))"/>
<!--执行环绕增强-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
测试类(这里动态代理的是接口!不能用实现类)
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理代理的是接口:注意点!
UserService userService = context.getBean("userService", UserService.class);
userService.add();
userService.delete();
}
方法二:自定义实现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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--方式二:自定义类-->
<bean id="diy" class="com.kun.diy.DiyPointCut"/>
<aop:config>
<!--自定义切面,ref:要引用的类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.kun.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
</beans>
测试类同上
方法三:使用注解实现AOP
切面类
//方式三 使用注解方式实现AOP
@Aspect//标注这个类是一个切面
public class annotationPointcut {
@Before("execution(* com.kun.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("====方法执行前====");
}
@After("execution(* com.kun.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("====方法执行后====");
}
//在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
@Around("execution(* com.kun.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("环绕前");
System.out.println("signature:"+joinPoint.getSignature());//获得签名
//执行方法
Object proceed = joinPoint.proceed();
System.out.println("环绕后");
System.out.println("proceed:"+proceed);
}
}
配置
<?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">
<!--方式三 注解实现AOP-->
<bean id="annotationPointCut" class="com.kun.diy.annotationPointcut"/><!--这里也可以用@Component-->
<!--开启AOP自动代理支持-->
<aop:aspectj-autoproxy/><!--可以使用@EnableAspectJAutoProxy-->
</beans>
测试结果
环绕前
signature:void com.kun.service.UserService.add()
====方法执行前====
增加了一个用户
====方法执行后====
环绕后
proceed:null
环绕前
signature:void com.kun.service.UserService.delete()
====方法执行前====
删除了一个用户
====方法执行后====
环绕后
proceed:null
拓展:
<!--
开启AOP自动代理注解支持! JDK(默认 proxy-targe-class="false") cglib(proxy-targe-class="true")
不同的实现方式,JDK为动态代理的方式,cglib基于类实现
-->
<aop:aspectj-autoproxy proxy-targe-class="false">
整合MyBatis
步骤:
-
导入相关jar包
- junit
- mybatis
- mysql数据库
- spring相关的
- aop织入
- mybatis-spring [new]
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.49</version> </dependency> <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.7</version> <scope>runtime</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.9</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.9</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> -
编写配置文件
-
测试
回顾MyBatis
-
编写实体类
@Data public class User { private int id; private String name; private String pwd; } -
编写核心配置文件
<?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核心配置文件--> <configuration> <!--别名--> <typeAliases> <package name="com.kun.pojo"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" 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="123456"/> </dataSource> </environment> </environments> <!--每一个Mapper.xml都需要在MyBatis核心配置文件中注册--> <mappers> <mapper resource="com/kun/dao/UserMapper.xml"/> </mappers> </configuration> -
编写接口
public interface UserMapper { List<User> selectUser(); } -
编写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.kun.mapper.UserMapper"> <select id="selectUser" resultType="user"> select * from user; </select> </mapper> -
编写测试
@Test public void mybatisTest() throws IOException { String configPath = "mybatis-config.xml"; InputStream is = Resources.getResourceAsStream(configPath); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sessionFactory.openSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> users = mapper.selectUser(); for (User user : users) { System.out.println(user); } }
MyBatis-Spring

原本的mybatis-config.xml文件可以完全被spring的配置取代,我们这里留下一个别名的配置放在mybatis-config.xml中,然后在spring的配置中引用这个配置文件,表示spring整合了mybatis。
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核心配置文件-->
<configuration>
<!--别名-->
<typeAliases>
<package name="com.kun.pojo"/>
</typeAliases>
</configuration>
配置方式一
-
编写数据源配置 [SqlSessionTemplate (线程安全)]
<!--DataSource:使用Spring的数据源替换MyBatis的配置 c3p0 dbcp druid 我们这里使用Spring提供的JDBC : org.springframework.jdbc.datasource --> <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="123456"/> </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/kun/mapper/**/*.xml"/> </bean> -
sqlSessionTemplate
<!--SqlSessionTemplate 就是我们使用的 SqlSession--> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法--> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> -
需要给接口加实现类
public class UserMapperImpl implements UserMapper{ //我们的所有操作,都使用sqlSession来执行,在原来、现在都使用sqlSessionTemplate private SqlSessionTemplate sqlSession; //设置set方法 这样就可以在配置文件中property方式注入 public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } @Override public List<User> selectUser() { UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.selectUser(); } } -
将自己写的实现类,注入到Spring中
<bean id="userMapper" class="com.kun.mapper.UserMapperImpl"> <property name="sqlSession" ref="sqlSession"/> </bean> -
测试
@Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper userMapper = context.getBean("userMapper", UserMapper.class); for (User user : userMapper.selectUser()) { System.out.println(user); } }
配置方式二 [SqlSessionDaoSupport 新方式]
-
编写数据源配置
<!--DataSource:使用Spring的数据源替换MyBatis的配置 c3p0 dbcp druid 我们这里使用Spring提供的JDBC : org.springframework.jdbc.datasource --> <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="123456"/> </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/kun/mapper/**/*.xml"/> </bean> -
需要给接口加实现类 [继承SqlSessionDaoSupport]
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper { @Override public List<User> selectUser() { return getSqlSession().getMapper(UserMapper.class).selectUser(); } } -
将自己写的实现类,注入到Spring中
<bean id="userMapper2" class="com.kun.mapper.UserMapperImpl2"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> -
测试
@Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper userMapper2 = context.getBean("userMapper2", UserMapper.class); for (User user : userMapper2.selectUser()) { System.out.println(user); } }
使用注解完成方式一二的配置
SpringDao
@Configuration
public class SpringDaoConfig {
@Bean
public DriverManagerDataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8");
dataSource.setUsername("root");
dataSource.setPassword("123456");
return dataSource;
}
@Bean
@Autowired
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws IOException {
SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
sessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
//资源匹配使用的类 一次性获取多个资源
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sessionFactoryBean.setMapperLocations(resolver.getResources("classpath:com/kun/mapper/**/*.xml"));
return sessionFactoryBean;
}
@Bean
@Autowired
public SqlSessionTemplate sqlSession(SqlSessionFactory sqlSessionFactory){
return new SqlSessionTemplate(sqlSessionFactory);
}
}
SpringConfig
@Configuration
@ComponentScan("com.kun")
@Import(SpringDaoConfig.class)
public class SpringConfig {
@Bean
@Autowired
public UserMapperImpl userMapper(SqlSessionTemplate sqlSession){
UserMapperImpl userMapper = new UserMapperImpl();
userMapper.setSqlSession(sqlSession);
return userMapper;
}
@Bean
@Autowired
public UserMapperImpl2 userMapper2(SqlSessionFactory sqlSessionFactory){
UserMapperImpl2 userMapperImpl2 = new UserMapperImpl2();
userMapperImpl2.setSqlSessionFactory(sqlSessionFactory);
return userMapperImpl2;
}
}
测试类
@Test
public void JavaConfigTest(){
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
System.out.println("==============================");
UserMapper userMapper2 = context.getBean("userMapper2", UserMapper.class);
for (User user : userMapper2.selectUser()) {
System.out.println(user);
}
}
总结:
-
导入其他配置 : @Import(配置类.class) 或 @ImportResource(“classpath:…xml”)
-
@Bean name="" 取别名, 方法名即id值
-
@Autowired 使用后变可以ref其他Bean,通过参数(参数名即ID名)传入
-
new ClassPathResource("") 以Resource返回一个资源文件
-
资源匹配使用的类 一次性获取多个资源
```java ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sessionFactoryBean.setMapperLocations(resolver.getResources("classpath:com/kun/mapper/**/*.xml")); ```
声明式事务
回顾事务
- 要么都成功,要么都失败!
- 事务在项目开发中,十分重要,涉及到数据的一致性问题,不能马虎!
- 确保完整性和一致性
事务ACID原则:
- 原子性 确保要么都成功,要么都失败
- 一致性 一旦事务完成,一键都提交
- 隔离性 多个业务可能操作同一个资源,防止数据损坏
- 持久性 事务一旦完成了,无论系统发生什么问题,结果都不再会被影响,被持久化的写到存储器中
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"/>
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务 通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给那些方法配置事务-->
<!--配置事务的传播特性:new-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<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.kun.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
思考:
为什么需要事务?
- 如果不配置事务,可能存在数据提交不一致的情况
- 如果我们不再Spring中配置声明式事务,我们就需要在代码中手动配置事务!
- 事务在项目的开发中十分重要,设计到数据的一致性和完整性完整性问题,不容马虎!
本博客参考 b站狂神说 制作
使用后变可以ref其他Bean,通过参数(参数名即ID名)传入
-
new ClassPathResource("") 以Resource返回一个资源文件
-
资源匹配使用的类 一次性获取多个资源
```java ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sessionFactoryBean.setMapperLocations(resolver.getResources("classpath:com/kun/mapper/**/*.xml")); ```
声明式事务
回顾事务
- 要么都成功,要么都失败!
- 事务在项目开发中,十分重要,涉及到数据的一致性问题,不能马虎!
- 确保完整性和一致性
事务ACID原则:
- 原子性 确保要么都成功,要么都失败
- 一致性 一旦事务完成,一键都提交
- 隔离性 多个业务可能操作同一个资源,防止数据损坏
- 持久性 事务一旦完成了,无论系统发生什么问题,结果都不再会被影响,被持久化的写到存储器中
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"/>
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务 通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给那些方法配置事务-->
<!--配置事务的传播特性:new-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<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.kun.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
思考:
为什么需要事务?
- 如果不配置事务,可能存在数据提交不一致的情况
- 如果我们不再Spring中配置声明式事务,我们就需要在代码中手动配置事务!
- 事务在项目的开发中十分重要,设计到数据的一致性和完整性完整性问题,不容马虎!
本博客参考 b站狂神说 制作
4万+

被折叠的 条评论
为什么被折叠?



