Spring
Spring是一个轻量级的IOC和AOP开源框架
IOC
IOC理论推导
在之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改源代码,如果程序代码量非常大 ,修改一次的成分代价十分昂贵
- 之前,程序是主动创建对象,控制权在程序员手上
- 使用了set注入之后,程序不再具有主动行,而是变成了被动的接受对象
这种思想,从本质上解决了问题,程序员不用再去管理对象的二创建,系统的耦合性大大的降低了, 可以专注的在业务上的实现这事ioc的原型
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UwbIyP87-1641801057430)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20211230161405818.png)]
IOC创建对象得方式
- 是哟个无参构造创建对象,默认!
- 假设我们要使用有参构造创建对象。
- 下标赋值
- 参数类型匹配
- 参数名
总结:在配置文件加载得时候,容器中管理得对象就已经初始化了
spring配置
别名
如果添加了别名我们也可以通过别名获取对象
Bean的配置
import
这个import,一般用于团队开发,它可以将多个配置文件,导入合并为一个 假设,现在项目中有多个人开发,这多个人负责不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个applicationContext.xml使用的时候
DI依赖注入
构造器注入
(说过了)
set方式注入
- 依赖注入:本质set注入
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器来注入
【环境搭建】
- 复杂类型
- 真实测试对象
- beans.xml
4. 测试类
拓展注入方式
我们可以使用c命名空间注入和c命名空间进行 注入
测试:
注意点:p命名空间和c命名空间不能直接使用,需要导入xml约束
bean 作用域
- 单例模式(Spring默认机制)
- 原型模式
- 其余的request、session、application这些只能在web开发中使用到
bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式!
- Spring会在上下文中自动寻找,并自动给bean装配属性
在Spring中有三种装配的方式
- 在xml中显示的配置
- 在java中显示配置
- 隐式的自动装配bean【重要】
ByName自动装配
ByType自动装配
小结:
- byName的时候,需要保证所有的bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
- byType的时候,需要保证所有的bean的class唯一,并且这个bean需要和自动注入的属性的类型一致
使用注解实现自动装配
jdk1.5支持的注解,Spring2.5就支持注解了
要使用注解须知:
- 导入配置
- 配置注解的支持:context:annotation-config
@Autowired
直接在属性上使用即可!也可以在set方法上使用
使用Autowired我们可以不用编写set方法了,前提是这个自动装配的属性在ioc容器中存在,且符合名字byName
科普:
@Nullable
如果显式的定义了Autowired的required属性为false,说明这个对象可以为false,说明这个对象可以为努力了,否则不许为空
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value="")去配置@Autowired的使用,指定唯一一个bean对象注入
@Resource注解
小结:
@Resource和@Autowired的区别
- 都是用来自动装配的,都可以放在属性字段上
- @Autowired通过byType方式实现,而且必须要求这个对象存在【常用】
- @Resource默认通过byname的方式实现,如果找不到名字,通过byType实现,如果两个都找不到就报错了
- 执行顺序不同,@Autowired通过byType的方式实现,@Resource默认通过byname的方式实现
使用注解开发
在spring4之后 ,要使用注解开发,必须要保证aop的包导入
使用注解需要导入context约束
bean
属性如何注入
@Component: 组件 放在类上,说明这个类被Spring容器管理了
@Value:
衍生的注解
@Component有几个衍生的注解,我们在web开发中会按照mvc三层架构分层
- dao【@Repository】
- service【@Service】
- Controller【@Controller】
这四个注解功能都是一样的,都是讲某个类注册到spring中,装配Bean
自动装配
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EuwvRVm9-1641801057447)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220105112207874.png)]
作用域
@Scope
小结
xml与注解
- xml更加万能,适用于任何场景!维护简单~
- 注解不是自己类使用不了,维护相对复杂
最佳实践:
- xml用来管理bean
- 注解只负责完成bean的注入,只需要注意一个问题:必须让注解生效,就需要开启注解的支持
使用java的方式配置Spring
我们现在要完全不适用spring的xml配置了,全权交给java来做!
JavaConfig是Spring的一个子项目,在Spring4之后,他成为了一个核心功能
@Configuration
这个也会被Spring容器托管,注册到容器中,因为本来就是一个@Component,@Configuration代表这是一个配置类,就和我们之前看的beans.xml同理
@ComponentScan
这个会代替Application去扫描bean注册的位置
@Bean
注册一个bean,就相当于我们之前的一个bean标签
这个方法的名字,就相当于bean标签中的id属性
这个方法的返回值,就相当于bean标签中的class属性
代理模式
为什么要学习代理模式?因为这就是springAOP的底层!
代理模式的分类:
- 静态代理
- 动态代理
静态代理的图例
静态代理
角色分析:
- 抽象角色:一般会使用接口或者抽象类来解决
- 真是角色:被代理的角色
- 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作
- 客户:访问对象的人
代理模式及的好处:
- 可以使真实角色更加纯粹!不用去关注一些公共的业务
- 公共也就是交给代理橘色,实现业务上的分工
- 公共业务发生扩展的时候,方便集中管理
缺点:
- 一个真实角色就会产生一个代理角色;代码量会翻倍,开发效率会变低
代码步骤:
接口
package com.qi.demo01;
/**
* 租房
*/
public interface Rent {
public void rent();
}
真实角色
package com.qi.demo01;
/**
* 房东
*/
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东要出租房子");
}
}
代理角色
package com.qi.demo01;
/**
* 代理角色
*/
public class Proxy implements Rent {
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
public void seeHose(){
System.out.println("中介带你看房");
}
public void hettong(){
System.out.println("签租赁合同");
}
public void fare(){
System.out.println("收中介费用");
}
@Override
public void rent() {
host.rent();
seeHose();
hettong();
fare();
}
}
客户端访问代理角色
package com.qi.demo01;
public class Client {
public static void main(String[] args) {
Proxy proxy = new Proxy(new Host());
proxy.rent();
}
}
动态代理
- 动态代理和静态代理角色一样
- 动态代理的代理类是动态生成的,不是我们写好的
- 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
- 预计接口—JDK动态代理
- 基于类:cglib
- java字节码实现:javasist
需要了解两个类:proxy(代理)、InvocationHandler(调用处理程序)
InvocationHandler
动态代理的好处:
- 可以使真是角色的操作更加纯粹,不用去关注一些公共的业务
- 公共也就交给代理角色,实现了业务的分工
- 公共业务发生扩展的时候方便集中进行管理
- 一个动态代理类代理的是一个接口,一般就是对应一类业务
- 一个动态代理类可以代理多个类,只要是实现了同一个接口即可
代码步骤
客户端访问代理角色
package com.qi.demo02;
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();
}
}
真实对象
package com.qi.demo02;
/**
* 房东 真实对象
*/
public class Host implements Rent {
@Override
public void rent() {
System.out.println("房东要出租房子");
}
}
接口
package com.qi.demo02;
/**
* 租房
*/
public interface Rent {
public void rent();
}
自动生成代理类
package com.qi.demo02;
import java.lang.annotation.Target;
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;
}
/**
* 生成得到代理类
* @return
*/
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
/**
* 处理代理实例,并返回结果
* @param proxy 代理对象
* @param method 方法
* @param args 参数
* @return 对象
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());
Object invoke = method.invoke(target, args);
return invoke;
}
public void seeHose(){
System.out.println("中介带看房子");
}
public void log(String msg){
System.out.println("执行了"+ msg + "方法。");
}
}
AOP
什么是AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能得统一维护的一种技术,AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生泛型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可用性,同时提高了开发的效率
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RONYc8NY-1641801057450)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220108114817069.png)]
AOP在Sprign中的作用
提供声明式事务;允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法后者功能。既是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等
- 切面(aspect):横切关注点被模块化的特殊对象,既,他是类的一个方法
- 通知(advice):切面必须要完成的工作,即,他是类中的一个方法
- 目标(target):被通知对象
- 代理(proxy):向目标对象应用通知之后创建的对象
- 切入点(PointCut):切面通知执行的“地点”的定义。
- 连接点(jointPoint):与切入点匹配的执行点。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-D0eAkCD8-1641801057450)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220108151847519.png)]
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
通知类型 | 连接点 | 实现接口 |
---|---|---|
前置通知 | 方法前 | org.springframework.aop.MethodBeforeAdvice; |
后置通知 | 方法后 | org.springframework.aop.AfterReturningAdvice; |
环绕通知 | 方法前后 | org.aopalliance.intercept.MethodInterceptor; |
异常抛出通知 | 方法抛出异常 | org.springframework.aop.ThrowsAdvice; |
引介通知 | 类中增加新的方法属性 | org.springframework.aop.IntroductionInterceptor; |
使用spring实现AOP
【重点】使用aop织入,需要导入一个依赖包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
方式一:使用spring得API接口
接口
package com.guo.service;
public interface UserService {
public void add();
public void update();
public void search();
public void delete();
}
实现类
package com.guo.service;
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("增加了一个用户");
}
@Override
public void update() {
System.out.println("更新了一个用户");
}
@Override
public void search() {
System.out.println("查询了一个用户");
}
@Override
public void delete() {
System.out.println("查询了一个用户");
}
}
日志
package com.guo.log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class Log implements MethodBeforeAdvice {
/*
* method:要执行目标对象的方法
* objects == args :参数
* o == target:目标对象
* */
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName() + "的" + method.getName()+ "被执行了");
}
}
package com.guo.log;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class AfterLog implements AfterReturningAdvice {
/*
* returnValue 返回值
* */
@Override
public void afterReturning(Object returnValue, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("执行了" + method.getName() + "返回结果为" + returnValue);
}
}
ApplicationContext.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userService" class="com.guo.service.UserServiceImpl"/>
<bean id="log" class="com.guo.log.Log"/>
<bean id="afterLog" class="com.guo.log.AfterLog"/>
<!--方式一:使用原生Spring API接口-->
<!--配置aop 需要导入aop约束-->
<aop:config>
<!--切入点:expression表达式,execution(要执行的位置 * * * * *)-->
<aop:pointcut id="pointcut" expression="execution(* com.guo.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
测试类
import com.guo.service.UserService;
import com.guo.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理的是接口
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}
}
方式二:自定义实现AOP【主要是切面定义】
自定义切面对象
package com.guo.diy;
public class DivPointCut {
public void before(){
System.out.println("方法执行前.....");
}
public void after(){
System.out.println("方法执行后.....");
}
}
xml配置
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userService" class="com.guo.service.UserServiceImpl"/>
<bean id="log" class="com.guo.log.Log"/>
<bean id="afterLog" class="com.guo.log.AfterLog"/>
<!--方式一:使用原生Spring API接口-->
<!--配置aop 需要导入aop约束-->
<!--<aop:config>
<!–切入点:expression表达式,execution(要执行的位置 * * * * *)–>
<aop:pointcut id="pointcut" expression="execution(* com.guo.service.UserServiceImpl.*(..))"/>
<!–执行环绕增加–>
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>-->
<!--方式二:自定义类-->
<bean id="diy" class="com.guo.diy.DivPointCut"/>
<aop:config>
<!--自定义切面,ref要引用得类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.guo.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
</beans>
接口
package com.guo.service;
public interface UserService {
public void add();
public void update();
public void search();
public void delete();
}
实现类
package com.guo.service;
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("增加了一个用户");
}
@Override
public void update() {
System.out.println("更新了一个用户");
}
@Override
public void search() {
System.out.println("查询了一个用户");
}
@Override
public void delete() {
System.out.println("查询了一个用户");
}
}
测试类
import com.guo.service.UserService;
import com.guo.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理的是接口
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}
}
方式三:使用注解实现
日志
package com.guo.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.guo.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("========方法执行前========");
}
@After("execution(* com.guo.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("======方法执行后========");
}
//在环绕增强中,我们可以给定一个参数,代表我们要处理切入的点
@Around("execution(* com.guo.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("=====环绕前=======");
Signature signature = jp.getSignature();
System.out.println("signature" + signature);
//执行方法
Object proceed = jp.proceed();
System.out.println("======环绕后=======");
System.out.println(proceed);
}
}
xml配置
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userService" class="com.guo.service.UserServiceImpl"/>
<bean id="log" class="com.guo.log.Log"/>
<bean id="afterLog" class="com.guo.log.AfterLog"/>
<!--方式三-->
<bean id="annotationPointCut" class="com.guo.diy.AnnotationPointCut"/>
<aop:aspectj-autoproxy/>
</beans>
测试类
import com.guo.service.UserService;
import com.guo.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理的是接口
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}
}
声明式事务
回顾事务
- 把一组业务当成一个业务,要么都成功要么都失败
- 事务在项目开发种,十分的重要,涉及到数据的一致性问题,不能马虎!
- 确保完整性和一致性
事务的ACID原则
- 原子性 要么都成功要么都失败
- 一致性 资源或者状态都总体保持不变,要么都提交要么都回滚
- 隔离性 多个事务可能操作同一个资源,防止数据损坏
- 持久性 事务一旦提交,无论发生什么问题,结果都不会再被影响,被持久化的写到存储器中
spring中得事务管理
-
声明式事务:aop
-
编程式事务:需要在代码中,进行事务的管理
为什么需要配置事务? -
如果不配置事务,可能存在数据提交不一致的情况
-
如果我们不在spring中去篇日志声明式事务,我们需要在代码中手动配置事务
-
事务在开发中十分重要,涉及到数据的一致性完整性。