什么是spring
Spring是分层的 Java SE/EE应用 full-stack 轻量级开源框架,以 IoC(Inverse Of Control:反转控制)和 AOP(Aspect Oriented Programming:面向切面编程)为内核。
spring的功能
简单来说,spring就是用来管理对象的,把对象的创建、初始化、销毁、对象间的相互依赖配置等工作交给spring容器来做,由spring容器控制对象的生命周期。
spring的优点
1)方便解耦,简化开发
通过 Spring提供的IoC容器,可以将对象间的依赖关系交由Spring进行控制,避免硬编码所造成的过度耦合。用户也不必再为单例模式类、属性文件解析等这些很底层的需求编写代码,可以更专注于上层的应用。
2)AOP 编程的支持
通过 Spring的 AOP 功能,方便进行面向切面编程,许多不容易用传统 OOP 实现的功能可以通过 AOP 轻松实现。
3)声明式事务的支持
可以将我们从单调烦闷的事务管理代码中解脱出来,通过声明式方式灵活的进行事务管理,提高开发效率和质量。
4)方便程序的测试
可以用非容器依赖的编程方式进行几乎所有的测试工作,测试不再是昂贵的操作,而是随手可做的事情。
5)方便集成各种优秀框架
Spring对各种优秀框架(Struts、Hibernate、Hessian、Quartz等)的支持。
6)降低 JavaEE API 的使用难度
Spring对 JavaEE API(如 JDBC、JavaMail、远程调用等)进行了薄薄的封装层,使这些 API 的使用难度大为降低。
7)Java 源码是经典学习范例
Spring的源代码设计精妙、结构清晰、匠心独用,处处体现着大师对Java 设计模式灵活运用以及对 Java技术的高深造诣。它的源代码无意是 Java 技术的最佳实践的范例。
快速入门
1.导入坐标
2.编写接口类及实现类
3.创建spring核心配置文件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"Index of /schema/beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="Index of /schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDao" class="com.jtyhnet.dao.impl.UserDaoImpl"/>
</beans>
4.使用Spring的API获得Bean实例
通过在applicationContext.xml中bean标签配置对应类,使用getBean()方法即可获得该类的对象进行操作。
spring配置文件解析
bean标签
Bean标签基本配置
用于配置对象交由Spring 来创建。
默认情况下它调用的是类中的无参构造函数,如果没有无参构造函数则不能创建成功。
基本属性:
id:Bean实例在Spring容器中的唯一标识
class:Bean的全限定名称
scope:指对象的作用范围,取值如下
singleton与prototype的区别
init-method:指定类中的初始化方法名称
destroy-method:指定类中销毁方法名称
Bean实例化三种方式
1.无参构造方法实例化
它会根据默认无参构造方法来创建类对象,如果bean中没有默认无参构造函数,将会创建失败
2.静态方法实例化
3.工厂实例方法实例化
Bean的依赖注入
案例:
service接口
service实现类,在实现类中调用dao的save方法
spring核心配置文件
进行测试
上述案例中,UserService实例和UserDao实例都存在于Spring容器中,当前的做法是在容器外部获得UserService实例和UserDao实例,然后在程序中进行结合。
由于UserService和UserDao都在Spring容器中,而最终程序直接使用的是UserService,所以可以在Spring容器中,将UserDao设置到UserService内部。
Bean的依赖注入概念
依赖注入(Dependency Injection):它是 Spring 框架核心 IOC 的具体实现。
在编写程序时,通过控制反转,把对象的创建交给了 Spring,但是代码中不可能出现没有依赖的情况。
IOC 解耦只是降低他们的依赖关系,但不会消除。例如:业务层仍会调用持久层的方法。
那这种业务层和持久层的依赖关系,在使用 Spring 之后,就让 Spring 来维护了。
简单的说,就是坐等框架把持久层对象传入业务层,而不用我们自己去获取。
Bean的依赖注入方式
1.set方法
需要使用哪个类的实例对象,就将该类的实例对象作为属性set到目标类中。
在spring核心配置文件中进行配置,在bean标签内部使用property标签注入相关属性
<?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="userDao" class="com.jtyhnet.dao.impl.UserDaoImpl"/>
<bean id="userService" class="com.jtyhnet.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
</beans>
Index of /schema/beans
Index of /schema/beans
Index of /schema/beans
除了使用property标签注入,也可以使用P命名空间注入,但比起上述的set方法注入更加方便,主要体现在配置文件中,先引入P命名空间 xmlns:p=“Not Found! ,然后在bean标签上即可进行配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="Not Found!"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDao" class="com.jtyhnet.dao.impl.UserDaoImpl"/>
<bean id="userService" class="com.jtyhnet.service.impl.UserServiceImpl" p:userDao-ref="userDao"/>
</beans>
2.构造方法
需要使用哪个类的实例对象,就将该类作为构造方法的参数
在配置文件中使用constructor-arg标签注入
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="Not Found!"
xsi:schemaLocation="Index of /schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDao" class="com.jtyhnet.dao.impl.UserDaoImpl"/>
<bean id="userService" class="com.jtyhnet.service.impl.UserServiceImpl">
<constructor-arg name="userDao" ref="userDao"/>
</bean>
</beans>
Bean的依赖的数据类型
注入数据的三种数据类型
- 普通数据类型
- 引用数据类型
- 集合数据类型
上述案例中注入的是引用Bean,即引用数据类型
1)普通数据类型注入
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"Not Found! xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="Index of /schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDao" class="com.jtyhnet.dao.impl.UserDaoImpl">
<property name="userId" value="1"/>
<property name="userName" value="tom"/>
</bean>
</beans>
1)集合数据类型注入
- 泛型为普通数据类型
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="Not Found!"
xsi:schemaLocation="Index of /schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDao" class="com.jtyhnet.dao.impl.UserDaoImpl">
<property name="stringList">
<list>
<value>zhangsan1</value>
<value>zhangsan2</value>
<value>zhangsan3</value>
</list>
</property>
</bean>
</beans>
- 泛型为引用类型
在list标签内部使用bean标签注入或者ref标签引用
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="Not Found!"
xsi:schemaLocation="Index of /schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDao" class="com.jtyhnet.dao.impl.UserDaoImpl">
<property name="userList">
<list>
<bean id="user1" class="com.jtyhnet.domain.User">
<property name="name" value="tom"/>
<property name="age" value="21"/>
</bean>
<bean id="user2" class="com.jtyhnet.domain.User">
<property name="name" value="abc"/>
<property name="age" value="23"/>
</bean>
</list>
</property>
</bean>
</beans>
使用ref引用
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"Index of /schema/beans xmlns:p="http://www.springframework.org/schema/p"Not Found! xmlns:p="http://www.springframework.org/schema/p"Index of /schema/beans xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user1" class="com.jtyhnet.domain.User">
<property name="name" value="tom"/>
<property name="age" value="22"/>
</bean>
<bean id="user2" class="com.jtyhnet.domain.User">
<property name="name" value="abc"/>
<property name="age" value="23"/>
</bean>
<bean id="userDao" class="com.jtyhnet.dao.impl.UserDaoImpl">
<property name="userList">
<list>
<ref bean="user1"/>
<ref bean="user2"/>
</list>
</property>
</bean>
</beans>
- Map类型集合注入
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="Not Found!"
xsi:schemaLocation="Index of /schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user1" class="com.jtyhnet.domain.User">
<property name="name" value="tom"/>
<property name="age" value="22"/>
</bean>
<bean id="user2" class="com.jtyhnet.domain.User">
<property name="name" value="abc"/>
<property name="age" value="23"/>
</bean>
<bean id="userDao" class="com.jtyhnet.dao.impl.UserDaoImpl">
<property name="userMap">
<map>
<entry key="user1" value-ref="user1"/>
<entry key="user2" value-ref="user2"/>
</map>
</property>
</bean>
</beans>
key 和 value 数值类型可以直接注入,引用类型可通过key-ref value-ref引入
- Properties注入
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"Not Found!<beans xmlns="Index of /schema/beansIndex of /schema/beans
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="Index of /schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDao" class="com.jtyhnet.dao.impl.UserDaoImpl">
<property name="properties">
<props>
<prop key="username">root</prop>
<prop key="password">root</prop>
</props>
</property>
</bean>
</beans>
引入其他配置文件(分模块开发)
实际开发中,Spring的配置内容非常多,这就导致Spring配置很繁杂且体积很大,所以,可以将部分配置拆解到其他配置文件中,而在Spring主配置文件通过import标签进行加载。
spring相关API
applicationContext:接口类型,代表应用上下文,可以通过其实例获得 Spring 容器中的 Bean 对象
- ApplicationContext的实现类
1.ClassPathXmlApplicationContext
它是从类的根路径下加载配置文件 推荐使用这种。
2.FileSystemXmlApplicationContext
它是从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置。
3.AnnotationConfigApplicationContext
当使用注解配置容器对象时,需要使用此类来创建 spring 容器。它用来读取注解。
- getBean()方法使用
Bean标签中,id是spring容器内的唯一标识,getBean(id)可以得到唯一对象,但需要强转;通过getBean(id,class)则不需要强转;getBean(class)仅在容器中只有该类的一个Bean时可用,若有多个相同类型的Bean则无法使用。
spring配置数据源
数据源(连接池)的作用
? 数据源(连接池)是提高程序性能如出现的
? 事先实例化数据源,初始化部分连接资源
? 使用连接资源时从数据源中获取
? 使用完毕后将连接资源归还给数据源
常见的数据源(连接池):DBCP、C3P0、BoneCP、Druid等
数据源手动创建
导入坐标
创建C3P0连接池
创建Druid连接池
为降低耦合性,jdbc连接信息提取到配置文件jdbc.properties
spring配置数据源
分析上述两个手动创建的连接池,都是使用无参构造创建,set方法注入配置,因此可以交给spring来进行创建。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="Index of /schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="c3P0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
</beans>
@Test
public void test3() throws SQLException {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
ComboPooledDataSource c3P0DataSource = applicationContext.getBean("c3P0DataSource", ComboPooledDataSource.class);
Connection connection = c3P0DataSource.getConnection();
System.out.println(connection);
System.out.println("------------------------------------");
DruidDataSource druidDataSource = applicationContext.getBean("druidDataSource", DruidDataSource.class);
DruidPooledConnection connection1 = druidDataSource.getConnection();
System.out.println(connection1);
}
为方便解耦,将applicationContext.xml中写死的值抽取到jdbc.properties配置文件中,使用context标签在applicationContext.xml中引入jdbc.properties。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"Index of /schema/context xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
Index of /schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
Index of /schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="jdbc.properties"/>
<bean id="c3P0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>
spring注解开发
Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率。
spring原始注解
Spring原始注解主要是替代<bean>的配置
使用注解进行开发时,需要在applicationContext.xml中配置组件扫描,作用是指定哪个包及其子包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="Index of /schema/context"
xsi:schemaLocation="
Index of /schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
Index of /schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="com.jtyhnet"/>
</beans>
使用@Compont或@Repository标识UserDaoImpl需要Spring进行实例化。
使用@Compont或@Service标识UserServiceImpl需要Spring进行实例化
使用@Autowired或者@Autowired+@Qulifier或者@Resource进行userDao的注入
使用@Value进行字符串的注入
使用@Scope标注Bean的范围
使用@PostConstruct标注初始化方法,使用@PreDestroy标注销毁方法
spring新注解
使用上面的注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下:
非自定义的Bean的配置:<bean>
加载properties文件的配置:<context:property-placeholder>
组件扫描的配置:<context:component-scan>
引入其他文件:<import>
spring注解配置数据源
使用@PropertySource引入配置文件,@Value注入数据,在获取数据源方法上使用@Bean将其存入spring容器。
spring注解将xml配置文件改为配置类
@Configuration标记该类为配置类
@ComponentScan配置注解扫描
@Import引入其他配置文件及非自定义对象的配置类(如数据源配置类)
spring整合junit
步骤
① 导入spring集成Junit的坐标
② 使用@Runwith注解替换原来的运行期
③ 使用@ContextConfiguration指定配置文件或配置类
④ 使用@Autowired注入需要测试的对象
⑤ 创建测试方法进行测试
面向切面编程AOP
spring的AOP简介
AOP 为 Aspect Oriented Programming 的缩写,意思为面向切面编程,是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
AOP 是 OOP 的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
- AOP 的作用及其优势
作用:在程序运行期间,在不修改源码的情况下对方法进行功能增强
优势:减少重复代码,提高开发效率,并且便于维护
- AOP 的底层实现
实际上,AOP 的底层是通过 Spring 提供的的动态代理技术实现的。在运行期间,Spring通过动态代理技术动态的生成代理对象,代理对象方法执行时进行增强功能的介入,在去调用目标对象的方法,从而完成功能的增强。
- 常用的动态代理技术
JDK 代理 : 基于接口的动态代理技术
cglib 代理:基于父类的动态代理技术
JDK动态代理
接口类
实现类
动态代理
cglib动态代理
实体类
动态代理
package com.jtyhnet.cglibProxy;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class CglibProxyTest {
public static void main(String[] args) {
//创建目标对象
Target target = new Target();
//创建增强器
Enhancer enhancer = new Enhancer();
//设置父类
enhancer.setSuperclass(Target.class);
//设置回调
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("前置增强cglib");
Object invoke = method.invoke(target, objects);
System.out.println("后置增强cglib");
return invoke;
}
});
Target proxy = (Target) enhancer.create();
proxy.method();
}
}
Spring 的 AOP 实现底层就是对上面的动态代理的代码进行了封装,封装后我们只需要对需要关注的部分进行代码编写,并通过配置的方式完成指定目标的方法增强。
AOP 的常用术语如下:
- Target(目标对象):代理的目标对象
- Proxy (代理):一个类被 AOP 织入增强后,就产生一个结果代理类
- Joinpoint(连接点):所谓连接点是指那些被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点
- Pointcut(切入点):所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义
- Advice(通知/ 增强):所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知
- Aspect(切面):是切入点和通知(引介)的结合
- Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程。spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入
AOP 开发明确的事项
1.需要编写的内容
- 编写核心业务代码(目标类的目标方法)
- 编写切面类,切面类中有通知(增强功能方法)
- 在配置文件中,配置织入关系,即将哪些通知与哪些连接点进行结合
2.AOP 技术实现的内容
Spring 框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。
3.AOP 底层使用哪种代理方式
在 spring 中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式。
知识要点
- aop:面向切面编程
- aop底层实现:基于JDK的动态代理 和 基于Cglib的动态代理
- aop的重点概念:
- Pointcut(切入点):被增强的方法
- Advice(通知/ 增强):封装增强业务逻辑的方法
- Aspect(切面):切点+通知
- Weaving(织入):将切点与通知结合的过程
- 开发明确事项:
- 谁是切点(切点表达式配置)
- 谁是通知(切面类中的增强方法)
- 将切点和通知进行织入配置
基于XML的AOP开发
快速入门
① 导入 AOP 相关坐标
② 创建目标接口和目标类(内部有切点)
③ 创建切面类(内部有增强方法)
④ 将目标类和切面类的对象创建权交给 spring
⑤ 在 applicationContext.xml 中配置织入关系
⑥ 测试代码
坐标导入
接口类
实现类
增强方法类
applicationContext.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="Index of /schema/context"
xmlns:aop="Index of /schema/aop"
xsi:schemaLocation="
Index of /schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
Index of /schema/context http://www.springframework.org/schema/context/spring-context.xsd
Index of /schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="target" class="com.jtyhnet.AOP.impl.Target"/>
<bean id="myAspect" class="com.jtyhnet.AOP.MyAspect"/>
<aop:config>
<aop:aspect ref="myAspect">
<aop:before method="before" pointcut="execution(public void com.jtyhnet.AOP.impl.Target.method())"/>
</aop:aspect>
</aop:config>
</beans>
测试
XML 配置 AOP 详解
切点表达式的写法
表达式语法:
execution([修饰符] 返回值类型 包名.类名.方法名(参数))
- 访问修饰符可以省略
- 返回值类型、包名、类名、方法名可以使用星号* 代表任意
- 包名与类名之间一个点 . 代表当前包下的类,两个点 . . 表示当前包及其子包下的类
- 参数列表可以使用两个点 . . 表示任意个数,任意类型的参数列表
Target类中method方法:execution(public void com.jtyhnet.AOP.impl.Target.method())
Target类中所有返回值void方法:execution(void com.jtyhnet.AOP.impl.Target.*(. .))
com.jtyhnet.AOP包下所有方法:execution(* com.jtyhnet.AOP.*.*(. .))
com.jtyhnet.AOP包及其子包下所有方法:execution(* com.jtyhnet.AOP. .*.*(. .))
当前工程下包及其子包下所有方法:execution(* *. .*.*(. .))
通知的类型
切点表达式抽取
当多个增强的切点表达式相同时,可以将切点表达式进行抽取,在增强中使用 pointcut-ref 属性代替 pointcut 属性来引用抽取后的切点表达式。
<aop:config>
<aop:aspect ref="myAspect">
<aop:pointcut id="targetPointcut" expression="execution(public void com.jtyhnet.AOP.impl.Target.method())"/>
<aop:before method="before" pointcut-ref="targetPointcut"/>
</aop:aspect>
</aop:config>
要点
通知的类型:前置通知、后置通知、环绕通知、异常抛出通知、最终通知
切点表达式的写法:
execution([修饰符] 返回值类型 包名.类名.方法名(参数))
基于注解的AOP开发
快速入门
基于注解的aop开发步骤:
① 创建目标接口和目标类(内部有切点)
② 创建切面类(内部有增强方法)
③ 将目标类和切面类的对象创建权交给 spring
④ 在切面类中使用注解配置织入关系
⑤ 在配置文件中开启组件扫描和 AOP 的自动代理
⑥ 测试
接口类
实现类@Component交给spring管理
切面类中配置织入
配置文件中开启注解扫描和AOP自动代理
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="Index of /schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"Index of /schema/context xmlns:aop="http://www.springframework.org/schema/aop"Index of /schema/beans xmlns:aop="http://www.springframework.org/schema/aop"Index of /schema/context xmlns:aop="Index of /schema/aophttp://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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.jtyhnet.AOPanno"/>
<aop:aspectj-autoproxy/>
</beans>
注解配置AOP详解
注解通知的类型
通知的配置语法:@通知注解(“切点表达式")
切点表达式的抽取
同 xml 配置 aop 一样,我们可以将切点表达式抽取。抽取方式是在切面内定义方法,在该方法上使用@Pointcut注解定义切点表达式,然后在在增强注解中进行引用。具体如下:
注解aop开发步骤
① 使用@Aspect标注切面类
② 使用@通知注解标注通知方法
③ 在配置文件中配置aop自动代理<aop:aspectj-autoproxy/>
Spring JdbcTemplate基本使用
JdbcTemplate概述
它是spring框架中提供的一个对象,是对原始繁琐的Jdbc API对象的简单封装。spring框架为我们提供了很多的操作模板类。例如:操作关系型数据的JdbcTemplate和HibernateTemplate,操作nosql数据库的RedisTemplate,操作消息队列的JmsTemplate等等。
JdbcTemplate开发步骤
① 导入spring-jdbc和spring-tx坐标
② 创建数据库表和实体
③ 创建JdbcTemplate对象
④ 执行数据库操作
Spring配置JdbcTemplate对象
@Test
public void testSpringJdbcTemplate() throws PropertyVetoException {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jdbcTemplate = applicationContext.getBean(JdbcTemplate.class);
//插入数据
jdbcTemplate.update("insert into account values(?,?)","lucy",5000);
//更新数据
jdbcTemplate.update("update account set money=? where name=?",1000,"tom");
//查询数据,返回结果集
List<Account> accounts = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
for (Account account : accounts) {
System.out.println(account.getName());
}
//查询单个对象
Account account = jdbcTemplate.queryForObject("select * from account where name=?", new BeanPropertyRowMapper<Account>(Account.class), "tom");
System.out.println(account.getName());
}
声明式事务控制
编程式事务控制相关对象
1.PlatformTransactionManager 接口是 spring 的事务管理器,它里面提供了我们常用的操作事务的方法。
注意:
PlatformTransactionManager 是接口类型,不同的 Dao 层技术则有不同的实现类,
例如:Dao 层技术是jdbc 或 mybatis 时:org.springframework.jdbc.datasource.DataSourceTransactionManager
Dao 层技术是hibernate时:org.springframework.orm.hibernate5.HibernateTransactionManager
2.TransactionDefinition 是事务的定义信息对象,里面有如下方法:
- 事务隔离级别
设置隔离级别,可以解决事务并发产生的问题,如脏读、不可重复读和虚读。
- 事务传播行为
REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
NEVER:以非事务方式运行,如果当前存在事务,抛出异常
NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行 REQUIRED 类似的操作
超时时间:默认值是-1,没有超时限制。如果有,以秒为单位进行设置
是否只读:建议查询时设置为只读
- TransactionStatus 接口提供的是事务具体的运行状态,方法介绍如下。
基于XML的声明式事务控制
Spring 的声明式事务顾名思义就是采用声明的方式来处理事务。这里所说的声明,就是指在配置文件中声明,用在 Spring 配置文件中声明式的处理事务来代替代码式的处理事务。
- 声明式事务处理的作用
- 事务管理不侵入开发的组件。具体来说,业务逻辑对象就不会意识到正在事务管理之中,事实上也应该如此,因为事务管理是属于系统层面的服务,而不是业务逻辑的一部分,如果想要改变事务管理策划的话,也只需要在定义文件中重新配置即可
- 在不需要事务管理的时候,只要在设定文件上修改一下,即可移去事务管理服务,无需改变代码重新编译,这样维护起来极其方便
Spring 声明式事务控制底层就是AOP。
声明式事务控制明确事项:
? 谁是切点?
? 谁是通知?
? 配置切面?
声明式事务控制的实现
转账案例:
依赖坐标
dao接口类
dao实现类
service接口类
service实现类
applicationContext.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="Index of /schema/aop"
xmlns:context="Index of /schema/context"
xmlns:tx="Index of /schema/tx"
xsi:schemaLocation="Index of /schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
Index of /schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
Index of /schema/context http://www.springframework.org/schema/context/spring-context.xsd
Index of /schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="userDao" class="com.jtyhnet.dao.impl.UserDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<bean id="userService" class="com.jtyhnet.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
</beans>
新建测试用account表
测试转账功能
查询数据库转账成功
按照事务控制的逻辑,转出和转入应该在一个事务内,如转出转入异常,则整个事务失败,两个用户的money不发生变化。
使用 int i = 1/0; 模拟异常进行测试
发现虽然报错,但转出操作仍完成,转入失败,需将转出转入配置一个事务。
1.xml中引入tx命名空间
2.配置transactionManager的bean,注入数据源dataSource
3.tx:advice配置事务增强,
使用<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
指定要增强的方法
4.要将事务控制和业务逻辑代码结合起来,使用aop织入实现事务增强
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="Index of /schema/aop"
xmlns:context="Index of /schema/context"
xmlns:tx="Index of /schema/tx"
xsi:schemaLocation="Index of /schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
Index of /schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
Index of /schema/context http://www.springframework.org/schema/context/spring-context.xsd
Index of /schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="userDao" class="com.jtyhnet.dao.impl.UserDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<bean id="userService" class="com.jtyhnet.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
<!--平台事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--事务增强配置-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!--配置事务AOP织入-->
<aop:config>
<aop:pointcut id="myPointcut" expression="execution(* com.jtyhnet.service.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"/>
</aop:config>
</beans>
还原表中数据后再次测试
实现整体控制
- <aop:aspect>与<aop:advisor>的区别
< aop:advisor>大多用于事务管理;<aop:aspect>用于普通切面,如日志等
<aop:advisor>需配置advice并注入;<aop:aspect>作用于具体的bean
- 切点方法的事务参数的配置
其中,<tx:method> 代表切点方法的事务参数的配置,例如:
<tx:method name=“transfer” isolation=“REPEATABLE_READ” propagation=“REQUIRED” timeout="-1" read-only=“false”/>
name:切点方法名称
isolation:事务的隔离级别
propogation:事务的传播行为
timeout:超时时间
read-only:是否只读
基于注解的声明式事务控制
先将案例改为注解开发,验证转账功能成功后再加入事务控制
参考XML配置逐步改为注解
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="Index of /schema/aop"
xmlns:context="Index of /schema/context"
xmlns:tx="Index of /schema/tx"
xsi:schemaLocation="Index of /schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
Index of /schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
Index of /schema/context http://www.springframework.org/schema/context/spring-context.xsd
Index of /schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="userDao" class="com.jtyhnet.dao.impl.UserDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<bean id="userService" class="com.jtyhnet.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
<!--平台事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--事务增强配置-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!--配置事务AOP织入-->
<aop:config>
<aop:pointcut id="myPointcut" expression="execution(* com.jtyhnet.service.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"/>
</aop:config>
</beans>
1.注解配置dataSource
2.注解配置JdbcTemplate
3.配置spring核心配置类
由于DataSource和JdbcTemplate都不是自定义类,使用@Import导入
4.配置dao,service
5.测试
查询数据库转账成功
加入注解配置声明式事务控制:
① 使用 @Transactional 在需要进行事务控制的类或是方法上修饰,注解可用的属性同 xml 配置方式,例如隔离级别、传播行为等。
② 注解使用在类上,那么该类下的所有方法都使用同一套注解参数配置。
③ 使用在方法上,不同的方法可以采用不同的事务参数配置。
④ Xml配置文件中要开启事务的注解驱动<tx:annotation-driven />
xml配置
<tx:annotation-driven transaction-manager=“transactionManager”/>,其中transaction-manager="transactionManager"可省略,默认情况下,<tx:annotation-driven>会自动使用名称为transactionManager的事务管理器。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="Index of /schema/tx"
xmlns:context="Index of /schema/context"
xsi:schemaLocation="Index of /schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
Index of /schema/context http://www.springframework.org/schema/context/spring-context.xsd
Index of /schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.jtyhnet"/>
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--平台事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--事务的注解驱动-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
测试
查询数据库确认转出转入都失败,事务得到控制
上述注解开发,为使@Transactional生效仍使用到了xml配置文件,注解改造不彻底,经分析发现
其实也是一个配置类,因此可以参考数据源配置类,单独写一个事务管理器配置类,在spring核心配置类中@import引入,使用@EnableTransactionManagement标签代替<tx:annotation-driven/>
事务管理器配置类
spring核心配置类
测试
事务得到控制
本文暂时没有评论,来添加一个吧(●'◡'●)