目录
索引
基本概念
- 耦合:程序间的依赖关系
- 类之间的依赖
- 方法之间的依赖
- 解耦:降低程序间的依赖关系
- 实际开发中应该做到:编译器不依赖,运行时才依赖。
- 解耦的思路:
- 使用反射创建对象,而避免使用new关键字
- 通过读取配置文件来获取创建的对象全限定类名
- Bean:在计算机英语中,有可重用组件的含义
- javabean:用java语言编写的bean。范围远大于实体类
创建Bean对象的工厂
- 建立配置文件
包含内容:唯一标志=全限定类名
配置文件可以是xml也可以是properties - 通过读取配置文件中的配置内容,反射创建对象
public class BeanFactory {
/**
*定义一个Properties对象
*/
private static Properties props;
/*
*使用静态代码块为Properties对象赋值
*/
static{
try {
//实例化对象
props = new Properties();
//获取properties文件的流对象
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
props.load(in);
} catch (Exception e) {
throw new ExceptionInInitializerError("初始化properties失败");
}
}
/**
*根据Bean的名称获取bean对象
*/
public static Object getBean(String beanName) {
Object bean = null;
try {
String beanPath = props.getProperty(beanName);
bean = Class.forName(beanPath).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return bean;
}
}
IOC
概念
控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),还有一种方式叫“依赖查找”(Dependency Lookup)。通过控制反转,对象在被创建的时候,由一个调控系统内所有对象的外界实体将其所依赖的对象的引用传递给它。也可以说,依赖被注入到对象中。
Class A中用到了Class B的对象b,一般情况下,需要在A的代码中显式的new一个B的对象。
采用依赖注入技术之后,A的代码只需要定义一个私有的B对象,不需要直接new来获得这个对象,而是通过相关的容器控制程序来将B对象在外部new出来并注入到A类里的引用中。而具体获取的方法、对象被获取时的状态由配置文件(如XML)来指定。
ApplicationContext的三个常用实现类
- ClassPathXmlApplicationContext:加载类路径下的配置文件,要求配置文件必须在类路径下
- FileSystemXmlApplicationContext:加载磁盘任意路径下的配置文件(必须有访问权限)
- AnnotationConfigApplicationContext:读取注解创建容器
ApplicationContext和BeanFactory的区别
-
ApplicationContext: 单例对象适用
它在构建核心容器时,创建对象采取的策略是采用立即加载的方式。也就是说,只要一读取完配置文件马上就创建配置文件中配置的对象。 -
BeanFactory: 多例对象使用
它在构建核心容器时,创建对象采取的策略是采用延迟加载的方式。也就是说,什么时候根据id获取对象了,什么时候才真正的创建对象。
Spring对Bean的管理细节
创建bean的三种方式
1. 使用默认构造函数创建
在spring的配置文件中使用bean标签,配以id和class属性之后,且没有其他属性和标签时。
采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则对象无法创建。
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
2. 使用普通工厂中的方法创建对象
使用某个类中的方法创建对象,并存入spring容器
<bean id="instanceFactory" class="com.itheima.factory.InstanceFactory"/>
<bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"/>
3. 使用工厂中的静态方法创建对象
使用某个类中的静态方法创建对象,并存入spring容器
<bean id="accountService" class="com.itheima.factory.StaticFactory" factory-method="getAccountService"/>
Bean的作用范围
bean标签的scope属性:
- 作用:用于指定bean的作用范围
- 取值: 常用的就是单例的和多例的
- singleton:单例的(默认值)
- prototype:多例的
- request:作用于web应用的请求范围
- session:作用于web应用的会话范围
- global-session:作用于集群环境的会话范围(全局会话范围),当不是集群环境时,它就是session
Bean的生命周期
- 单例对象
出生:当容器创建时对象出生
活着:只要容器还在,对象一直活着
死亡:容器销毁,对象消亡
总结:单例对象的生命周期和容器相同 - 多例对象
出生:当我们使用对象时spring框架为我们创建
活着:对象只要是在使用过程中就一直活着。
死亡:当对象长时间不用,且没有别的对象引用时,由Java的垃圾回收器回收
依赖注入Dependency Injection
在当前类中需要用到其他类的对象,由spring为我们提供,我们只需要在配置文件中说明
能注入的数据,有三类:
- 基本类型和String
- 其他bean类型(在配置文件中或者注解配置过的bean)
- 复杂类型/集合类型
注入的方式:有三种
- 使用构造函数提供
- 使用set方法提供
- 使用注解提供
构造函数注入:
使用的标签:constructor-arg
标签出现的位置:bean标签的内部
标签中的属性
- type:用于指定要注入的数据的数据类型,该数据类型也是构造函数中某个或某些参数的类型
- index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值。索引的位置是从0开始
- name:用于指定给构造函数中指定名称的参数赋值
以上三个用于指定给构造函数中哪个参数赋值
- value:用于提供基本类型和String类型的数据
- ref:用于指定其他的bean类型数据。它指的就是在spring的Ioc核心容器中出现过的bean对象
1 优势:
在获取bean对象时,注入数据是必须的操作,否则对象无法创建成功。
2 弊端:
改变了bean对象的实例化方式,使我们在创建对象时,如果用不到这些数据,也必须提供。
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<constructor-arg name="name" value="泰斯特"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
<constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>
<!-- 配置一个日期对象 -->
<bean id="now" class="java.util.Date"></bean>
set方法注入
-
涉及的标签:property
-
出现的位置:bean标签的内部
-
标签的属性
- name:用于指定注入时所调用的set方法名称
- value:用于提供基本类型和String类型的数据
- ref:用于指定其他的bean类型数据。它指的就是在spring的Ioc核心容器中出现过的bean对象
-
优势:
创建对象时没有明确的限制,可以直接使用默认构造函数 -
弊端:
如果有某个成员必须有值,则获取对象时有可能set方法没有执行。
<bean id="accountService2" class="com.itheima.service.impl.AccountServiceImpl2">
<property name="name" value="TEST" ></property>
<property name="age" value="21"></property>
<property name="birthday" ref="now"></property>
</bean>
复杂类型的注入/集合类型的注入
- 用于给List结构集合注入的标签:
list array set - 用于个Map结构集合注入的标签:
map props
结构相同,标签可以互换
<bean id="accountService3" class="com.itheima.service.impl.AccountServiceImpl3">
<property name="myStrs">
<set>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</set>
</property>
<property name="myList">
<array>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</array>
</property>
<property name="mySet">
<list>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</list>
</property>
<property name="myMap">
<props>
<prop key="testC">ccc</prop>
<prop key="testD">ddd</prop>
</props>
</property>
<property name="myProps">
<map>
<entry key="testA" value="aaa"></entry>
<entry key="testB">
<value>BBB</value>
</entry>
</map>
</property>
</bean>
IOC注解
使用注解,要在xml配置文件中告知spring在创建容器时要扫描的包。
<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/context/spring-context.xsd">
<!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为
context名称空间和约束中-->
<context:component-scan base-package="com.itheima"></context:component-scan>
</beans>
用于创建对象
他们的作用就和在XML配置文件中编写一个<bean>
标签实现的功能是一样的
-
Component: 也可使用Named
作用:用于把当前类对象存入spring容器中
属性:- value:用于指定bean的id。当我们不写时,它的默认值是当前类名,且首字母改小写。
-
Controller:一般用在表现层
-
Service:一般用在业务层
-
Repository:一般用在持久层
以上三个注解他们的作用和属性与Component是一模一样。
他们三个是spring框架为我们提供明确的三层使用的注解,使我们的三层对象更加清晰
用于注入数据
他们的作用就和在xml配置文件中的bean标签中写一个<property>
标签的作用是一样的
- Autowired:
- 作用:自动按照类型注入。只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错。
如果Ioc容器中有多个类型匹配时:使用变量名称进行进一步的查找,如果没有与变量名称一样的,则报错 - 出现位置:
可以是变量上,也可以是方法上 - 细节:
在使用注解注入时,set方法就不是必须的了。
- 作用:自动按照类型注入。只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
- Qualifier:
- 作用:在按照类中注入的基础之上再按照名称注入。它在给类成员注入时不能单独使用,必须与@Autowired配合使用。但是在给方法参数注入时可以
- 属性:
value:用于指定注入bean的id。
- Resource
- 作用:直接按照bean的id注入。它可以独立使用
- 属性:
name:用于指定bean的id。
以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现。
另外,集合类型的注入只能通过XML来实现。
- Value
- 作用:用于注入基本类型和String类型的数据
- 属性:
value:用于指定数据的值。它可以使用spring中SpEL(也就是spring的el表达式)
SpEL的写法:${表达式}
用于改变作用范围
他们的作用就和在bean标签中使用scope属性实现的功能是一样的
- Scope
- 作用:用于指定bean的作用范围
- 属性:
value:指定范围的取值。常用取值:singleton(默认情况,单例) prototype(多例)
和生命周期相关
他们的作用就和在bean标签中使用init-method
和destroy-methode
的作用是一样的
- PreDestroy
作用:用于指定销毁方法 - PostConstruct
作用:用于指定初始化方法
配置类,取代xml文件
该类是一个配置类,它的作用和bean.xml是一样的
Configuration
作用:指定当前类是一个配置类
细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该配置类的此注解可以不写。
ComponentScan
作用:用于通过注解指定spring在创建容器时要扫描的包,如果不写则默认扫描配置类所在的包
属性:
value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。
@Configutation
@ComponentScan(basePackages={"com.itheima","xxx"})//@ComponentScan("com.itheima")
所设置的基础包是以String类型表示的,是类型不安全的,重构代码后可能会出错。
可以将其指定为包中所包含的类或者接口:
可以在保重创建一个用来进行扫描的空标记接口,这样重构时将对此不造成影响。
@Configutation
@ComponentScan(basePackageClasses={market.class})
使用此注解就等同于在xml中配置了:
<context:component-scan base-package="com.itheima"></context:component-scan>
Bean
作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
属性:
name:用于指定bean的id。当不写时,默认值是当前方法的名称
细节:
当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象。
查找的方式和Autowired注解是一样的
Import
作用:用于导入其他的配置类
属性:
value:用于指定其他配置类的字节码。
当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类
PropertySource
作用:用于指定properties文件的位置
属性:
value:指定文件的名称和路径。
关键字:classpath,表示类路径下
@PropertySource("classpath:xxxx.properties")
配置类获取IOC容器
方法1
ApplicationContext ac = AnnotationConfigApplicationContext(SpringConfiguration.class);
方法2
@ContextConfiguration(classes = SpringConfiguration.class)
动态代理
- 特点:字节码随用随创建,随用随加载
- 作用:不修改源码的基础上对方法增强
- 分类:
- 基于接口的动态代理
- 基于子类的动态代理
基于接口的动态代理:
- 涉及的类:Proxy
提供者:JDK官方 - 如何创建代理对象:
使用Proxy类中的newProxyInstance方法 - 创建代理对象的要求:
被代理类最少实现一个接口,如果没有则不能使用 - newProxyInstance方法的参数:
- ClassLoader:类加载器
它是用于加载代理对象字节码的。和被代理对象使用相同的类加载器。固定写法。 - Class[]:字节码数组
它是用于让代理对象和被代理对象有相同方法。固定写法。 - InvocationHandler:用于提供增强的代码
它是让我们写如何代理。我们一般都是些一个该接口的实现类,通常情况下都是匿名内部类,但不是必须的。
此接口的实现类都是谁用谁写。
- ClassLoader:类加载器
public class Client {
public static void main(String[] args) {
final Producer producer = new Producer();
IProducer proxyProducer = (IProducer) Proxy.newProxyInstance(producer.getClass().getClassLoader(),
producer.getClass().getInterfaces(),
new InvocationHandler() {
/**
* 执行被代理对象的任何接口的方法都会经过该方法
* @param proxy 代理对象的引用
* @param method 当前执行的方法
* @param args 当前执行方法所需的参数
* @return 和被代理对象有相同的返回值
* @throws Throwable
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//提供增强的代码
Object returnValue = null;
//1.获取方法执行的参数
Float money = (Float) args[0];
//2.判断当前方法是不是销售
if ("saleProduct".equals(method.getName())) {
returnValue = method.invoke(producer, money*0.8f);
}
return returnValue;
}
});
proxyProducer.saleProduct(10000f);
}
}
基于子类的动态代理
- 涉及的类:Enhancer
提供者:第三方cglib库 - 如何创建代理对象:
使用Enhancer类中的create方法 - 创建代理对象的要求:
被代理类不能是最终类 - create方法的参数:
-
Class:字节码
它是用于指定被代理对象的字节码。 -
Callback:用于提供增强的代码
它是让我们写如何代理。我们一般都是些一个该接口的实现类,通常情况下都是匿名内部类,但不是必须的。
此接口的实现类都是谁用谁写。
我们一般写的都是该接口的子接口实现类:MethodInterceptor
-
public class Client {
public static void main(String[] args) {
final Producer producer = new Producer();
Producer cglibproducer = (Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() {
/**
* 执行被代理对象的任何方法都会经过该方法
* @param proxy
* @param method
* @param args
* 以上三个参数和基于接口的动态代理中invoke方法的参数是一样的
* @param methodProxy :当前执行方法的代理对象
* @return
* @throws Throwable
*/
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
//提供增强的代码
Object returnValue = null;
//1.获取方法执行的参数
Float money = (Float) args[0];
//2.判断当前方法是不是销售
if ("saleProduct".equals(method.getName())) {
returnValue = method.invoke(producer, money * 0.8f);
}
return returnValue;
}
});
cglibproducer.saleProduct(120000f);
}
}
动态代理实现事务
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("test".equals(method.getName())){
return method.invoke(accountService,args);
}
Object rtValue = null;
try {
//1.开启事务
txManager.beginTransaction();
//2.执行操作
rtValue = method.invoke(accountService, args);
//3.提交事务
txManager.commit();
//4.返回结果
return rtValue;
} catch (Exception e) {
//5.回滚操作
txManager.rollback();
throw new RuntimeException(e);
} finally {
//6.释放连接
txManager.release();
}
}
Spring中的AOP
Aspect-oriented programming面向接口编程,
通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。
- 作用:
在程序运行期间,不修改源码对已有方法进行增强 - 优势:
减少重复代码
提高开发效率
维护方便
AOP相关术语
-
Joinpoint(连接点): 所谓连接点是指那些被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点。
-
Pointcut(切入点): 所谓切入点是指我们要对哪些Joinpoint进行拦截的定义。
-
Advice(通知/增强): 所谓通知是指拦截到Joinpoint之后所要做的事情就是通知。 通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。
-
Introduction(引介): 引介是一种特殊的通知在不修改类代码的前提下, Introduction可以在运行期为类动态地添加一些方法或Field。
-
Target(目标对象): 代理的目标对象。
-
Weaving(织入): 是指把增强应用到目标对象来创建新的代理对象的过程。 spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入。
-
Proxy(代理): 一个类被AOP织入增强后,就产生一个结果代理类。
-
Aspect(切面): 是切入点和通知(引介)的结合。
XML配置AOP
<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">
<!-- 配置spring的Ioc-->
<bean id="accountService" class="wewe.bad.service.impl.AccountServiceImpl"/>
<!-- spring基于xml的AOP配置-->
<!-- 1. 把通知Bean也交给spring来管理-->
<!-- 配置Logger类-->
<bean id="logger" class="wewe.bad.utils.Logger"/>
<!-- 2. 使用aop:config标签表明开始AOP的配置-->
<!-- 配置AOP-->
<aop:config>
<!-- 3. 使用aop:aspect标签配置切面
id属性:是给切面提供一个唯一的标识
ref属性:是指定通知类bean的id
-->
<aop:aspect id="logAdvice" ref="logger">
<!-- 4. 在aop:aspect标签的内部使用对应标签配置通知的类型
我们想让printLog方法在切入点方法执行之前,所以是前置通知
aop:before:表示前置通知
method属性:用于指定类中哪个方法是前置通知
pointcut属性:用于指定切入点表达式,该表达式的含义是指对业务层中的哪个方法进行增强
切入点报答是的写法:
关键字:execution(表达式)
表达式:
访问修饰符 返回值 包名.包名..... 类名.方法名(参数列表)
eg:public void wewe.bad.service.impl.AccountServiceImpl.saveAccount()
-->
<aop:before method="printLog"
pointcut="execution(public void wewe.bad.service.impl.AccountServiceImpl.saveAccount())"/>
</aop:aspect>
</aop:config>
</beans>
切入点表达式的写法
标准写法:
public void wewe.bad.service.impl.AccountServiceImpl.saveAccount()
全通配写法:所有方法都配置
* *..*.*(..)
权限修饰符可以省略
void wewe.bad.service.impl.AccountServiceImpl.saveAccount()
返回值可以使用通配符表示任意返回值
* wewe.bad.service.impl.AccountServiceImpl.saveAccount()
包名可以使用通配符表示任意包,但几级包就需要写几个*
也可以用…表示当前包及其子包
* *.*.*.*.AccountServiceImpl.saveAccount()
* *..AccountServiceImpl.saveAccount()
类名和方法名都可以使用*实现统配
* *..*.saveAccount()
* *..*.*()
参数列表:
- 可以直接写数据类型:
基本类型直接写名称:int
引用类型写包名.类名的方式:java.lang.String - 可以使用
*
表示任意类型,但必须有参数 - 可以使用
..
表示有无参数即可
* *..*.*(..)
四种通知
<aop:before method="beforePrintLog"
pointcut="execution(public void wewe.bad.service.impl.*.*(..))"/>
<aop:after-returning method="afterReturningPrintLog"
pointcut="execution(public void wewe.bad.service.impl.*.*(..))"/>
<aop:after-throwing method="afterThrowingPrintLog"
pointcut="execution(public void wewe.bad.service.impl.*.*(..))"/>
<aop:after method="afterPrintLog"
pointcut="execution(public void wewe.bad.service.impl.*.*(..))"/>
配置切入点表达式
<!-- 配置切入点表达式 id属性用于指定表达式的唯一标识。expression属性用于指定表达式内容
此标签写在aop:aspect标签内部只能当前切面使用。
它还可以写在aop:aspect外面,此时就变成了所有切面可用
-->
<aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut>
<aop:aspect id="logAdvice" ref="logger">
<aop:before method="beforePrintLog" pointcut-ref="pt1" ></aop:before>
<aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>
<aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>
<aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>
</aop:aspect>
环绕通知
<aop:around method="aroundPringLog" pointcut-ref="pt1"></aop:around>
/**
* 环绕通知
* 问题:
* 当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了。
* 分析:
* 通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有。
* 解决:
* Spring框架为我们提供了一个接口:ProceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于明确调用切入点方法。
* 该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用。
*
* spring中的环绕通知:
* 它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式。
*/
public Object aroundPringLog(ProceedingJoinPoint pjp){
Object rtValue = null;
try{
Object[] args = pjp.getArgs();//得到方法执行所需的参数
System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。前置");
rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)
System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。后置");
return rtValue;
}catch (Throwable t){
System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。异常");
throw new RuntimeException(t);
}finally {
System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。最终");
}
}
基于注解的AOP
Spring基于注解的AOP中,这4个通知的执行调用顺序存在问题
<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"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置spring创建容器时要扫描的包-->
<context:component-scan base-package="wewe.bad"/>
<!-- 配置spring开启注解AOP的支持-->
<aop:aspectj-autoproxy/>
</beans>
@Component("logger")
@Aspect//表示当前类是一个切面类
@Pointcut("execution(public void wewe.bad.service.impl.*.*(..))")
private void pt1() {}
@Before("pt1()")
@AfterReturning("pt1()")
@AfterThrowing("pt1()")
@After("pt1()")
@Arround("pt1()")
不使用XML的配置方式
@Configuration
@ComponentScan(basePackages="com.itheima")
@EnableAspectJAutoProxy
public class SpringConfiguration { }