文章目录
Spring简介
Spring是什么
Spring 是分层的 Java SE/EE 应用 full-stack 轻量级开源框架,以 IoC(Inverse Of Control:反转控制)和 AOP(Aspect Oriented Programming:面向切面编程)为内核,提供了展现层 SpringMVC 和持久层 Spring JDBC 以及业务层事务管理等众多的企业级应用技术,还能整合开源世界众多著名的第三方框架和类库,逐渐成为使用最多的 Java EE 企业应用开源框架。
Spring的发展历程
- 1997 年 IBM 提出了 EJB 的思想
- 1998 年,SUN 制定开发标准规范 EJB1.0
- 1999 年,EJB1.1 发布
- 2001 年,EJB2.0 发布
- 2003 年,EJB2.1 发布
- 2006 年,EJB3.0 发布
- Rod Johnson(spring 之父)
Expert One-to-One J2EE Design and Development(2002)
阐述了 J2EE 使用 EJB 开发设计的优点及解决方案
Expert One-to-One J2EE Development without EJB(2004)
阐述了 J2EE 开发不使用 EJB 的解决方式(Spring 雏形) - 2017 年 9 月份发布了 spring 的最新版本 spring 5.0 通用版(GA)
Spring 的优势
- 方便解耦,简化开发
通过 Spring 提供的 IoC 容器,可以将对象间的依赖关系交由 Spring 进行控制,避免硬编码所造成的过度程序耦合。用户也不必再为单例模式类、属性文件解析等这些很底层的需求编写代码,可以更专注于上层的应用。 - AOP 编程的支持
通过 Spring 的 AOP 功能,方便进行面向切面的编程,许多不容易用传统 OOP 实现的功能可以通过 AOP 轻松应付。 - 声明式事务的支持
可以将我们从单调烦闷的事务管理代码中解脱出来,通过声明式方式灵活的进行事务的管理,提高开发效率和质量。 - 方便程序的测试
可以用非容器依赖的编程方式进行几乎所有的测试工作,测试不再是昂贵的操作,而是随手可做的事情。 - 方便集成各种优秀框架
Spring 可以降低各种框架的使用难度,提供了对各种优秀框架(Struts、Hibernate、Hessian、Quartz等)的直接支持。 - 降低 JavaEE API 的使用难度
Spring 对 JavaEE API(如 JDBC、JavaMail、远程调用等)进行了薄薄的封装层,使这些 API 的使用难度大为降低。 - Java 源码是经典学习范例
Spring 的源代码设计精妙、结构清晰、匠心独用,处处体现着大师对 Java 设计模式灵活运用以及对 Java 技术的高深造诣。它的源代码无意是 Java 技术的最佳实践的范例。
Spring的体系结构
Spring解耦
解耦的思路:
当我们使用jdbc 时,是通过反射来注册驱动的,代码如下:
Class.forName("com.mysql.jdbc.Driver");//此处只是一个字符串
此时的好处是,我们的类中不再依赖具体的驱动类,此时就算删除 mysql 的驱动 jar 包,依然可以编译(运行就不要想了,没有驱动不可能运行成功的)。同时,也产生了一个新的问题,mysql 驱动的全限定类名字符串是在 java 类中写死的,一旦要改还是要修改源码。解决这个问题也很简单,使用配置文件配置。
在实际开发中我们可以把三层的对象都使用配置文件配置起来,当启动服务器应用加载的时候,让一个类中的方法通过读取配置文件,把这些对象创建出来并存起来。在接下来的使用的时候,直接拿过来用就好了。那么,这个读取配置文件,创建和获取三层对象的类就是工厂。
解耦的思路有 2 个问题:
- 存哪去?
分析:由于我们是很多对象,肯定要找个集合来存。这时候有 Map 和 List 供选择。 到底选 Map 还是 List 就看我们有没有查找需求。有查找需求,选 Map。所以我们的答案就是在应用加载时,创建一个 Map,用于存放三层对象。我们把这个 map 称之为容器。 - 什么是工厂?
工厂就是负责给我们从容器中获取指定对象的类。这时候我们获取对象的方式发生了改变。
原来:
我们在获取对象时,都是采用 new 的方式。是主动的。
现在:
我们获取对象时,同时跟工厂要,有工厂为我们查找或者创建对象。是被动的。
反转控制:
控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),还有一种方式叫“依赖查找”(Dependency Lookup)。把创建对象的权力交给对象是框架最重要的特征。
Spring开发步骤
- 导入坐标
- 创建Bean
- 创建applicationContext.xml
- 在配置文件中进行配置
- 创建ApplicationContext对象getBean
Spring配置文件
Bean标签基本配置
作用:用于配置对象交由Spring来创建。
基本属性:
-
id: Bean实例在Spring容器中的唯一标识
-
class: Bean的全限定名称
默认情况下它调用的是类中的无参构造函数,如果没有无参构造函数则不能创建成功。 -
scope:指对象的作用范围,取值如下:
scope的取值 | singleton | prototype |
---|---|---|
Bean的实例化个数 | 1个 | 多个 |
Bean的实例化时机 | 当Spring核心文件被加载时(容器创建时),实例化配置的Bean实例 | 当调用getBean()方法时实例化Bean |
对象运行 | 只要容器在,对象一直活着 | 只要对象在使用中,就一直活着 |
对象销毁 | 当应用卸载,销毁容器时,对象就被销毁了 | 当对象长时间不用时,被Java的垃圾回收器回收了 |
- init-method:指定类中的初始化方法名称
- destroy-method:指定类中销毁方法名称
Bean实例化三种方式
- 无参构造方法实例化
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl" ></bean>
- 工厂静态方法实例化
<bean id="userDao" class="com.itheima.factory.StaticFactory" factory-method="getUserDao"></bean>
- 工厂实例方法实例化
<bean id="factory" class="com.itheima.factory.DynamicFactory"></bean>
<bean id="userDao" factory-bean="factory" factory-method="getUserDao"></bean>
Bean的依赖注入概念
问题的引入:
在没有使用依赖注入的情况下,UserService实例和UserDao实例都存在与Spring容器中,当前的做法是在容器外部获得UserService实例和UserDao实例,然后在程序中进行结合。
因为UserService和UserDao都在Spring容器中,而最终程序直接使用的是UserService,所以可以在Spring容器中,将UserDao设置到UserService内部。
-
依赖注入(DependencyInjection):它是Spring框架核心lOC的具体实现。
-
在编写程序时,通过控制反转,把对象的创建交给了Spring,但是代码中不可能出现没有依赖的情况。
IOC解耦只是降低他们的依赖关系,但不会消除。例如:业务层仍会调用持久层的方法。 -
那这种业务层和持久层的依赖关系,在使用Spring之后,就让Spring来维护了。简单的说,就是坐等框架把持久层对象传入业务层,而不用我们自己去获取。
Bean的依赖注入方式:
- 构造方法注入
service层代码:
public class UserServiceImpl implements UserService {
private UserDao userDao;
public UserServiceImpl(UserDao userDao) {
this.userDao = userDao;
}
public UserServiceImpl() {
}
// public void setUserDao(UserDao userDao){
// this.userDao = userDao;
// }
public void save() {
userDao.save();
}
}
配置文件写法:
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl" ></bean>
<bean id="userService" class="com.itheima.service.Impl.UserServiceImpl">
<constructor-arg name="userDao" ref="userDao"></constructor-arg>
</bean>
name是属性名,ref是要实例化的bean的id。
- set方法注入
service层代码:
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao){
this.userDao = userDao;
}
public void save() {
userDao.save();
}
}
配置文件的写法:
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl" ></bean>
<bean id="userService" class="com.itheima.service.Impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
其中一个property标签一个属性的注入依赖,name是属性名,ref是要实例化的bean的id。这样配置后,在实例化时会自动调用对象的set方法。
当service层使用了依赖注入后,就不能再通过new的方式进行获取对象,因为通过new的方式获取对象userDao属性没有实例化,会出现空指针异常。
两种注入方法的区别:
两种依赖方式都可以使用,构造器注入和Setter方法注入。最好的解决方案是用构造器参数实现强制依赖,setter方法实现可选依赖。
- P命名空间注入
P命名空间注入本质也是set方法注入,但比起上述的set方法注入更加方便,主要体现在配置文件中,如下:
首先,需要引入P命名空间:
其次,需要修改注入方式
上面的操作,都是注入的引用Bean,处了对象的引回以注入,普通数据类型,集合等都可以在容器中进行注入。这里使用set方式注入进行举例。
注入数据的三种数据类型
- 普通数据类型
userDaoImpl中的代码:
private String username;
private int age;
public void setUsername(String username) {
this.username = username;
}
public void setAge(int age) {
this.age = age;
}
配置文件的写法:
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl" >
<property name="username" value="zhangsan"/>
<property name="age" value="18"/>
</bean>
注意普通数据和引用数据的区别,引用数据使用的时ref,普通数据使用的时value。
- 引用数据类型
和bean的依赖注入相同 - 集合数据类型
UserDaoImpl中的写法:
private List<String> strList;
private Map<String, User> userMap;
private Properties properties;
public void setStrList(List<String> strList) {
this.strList = strList;
}
public void setUserMap(Map<String, User> userMap) {
this.userMap = userMap;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
配置文件中的写法:
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl" >
<property name="strList">
<list>
<value>aaa</value>
<value>bbb</value>
<value>ccc</value>
</list>
</property>
<property name="userMap">
<map>
<entry key="u1" value-ref="user1"></entry>
<entry key="u2" value-ref="user2"></entry>
</map>
</property>
<property name="properties">
<props>
<prop key="p1">ppp1</prop>
<prop key="p2">ppp2</prop>
<prop key="p3">ppp3</prop>
</props>
</property>
</bean>
<bean name="user1" class="com.itheima.domain.User">
<property name="name" value="tom"></property>
<property name="addr" value="beijing"></property>
</bean>
<bean name="user2" class="com.itheima.domain.User">
<property name="name" value="lucy"></property>
<property name="addr" value="tianjin"></property>
</bean>
引入其他配置文件(分模块开发)
实际开发中,Spring的配置内容非常多,这就导致Spring配置很繁杂且体积很大 ,所以,可以将部分配置拆解到其他配置文件中,而在Spring主配置文件通过import标签进行加载。
<import resource="applicationContext-xxx.xml"/>
配置文件总结
Spring相关API
ApplicationContext的继承体系
applicationContext
:接口类型,代表应用上下文,可以通过其实例获得Spring容器中的Bean对象。
图中,紫色的表示接口,淡青色的表示抽象类,深青色的表示可实例化的类。
ApplicationContext的实现类
ClassPathXmlApplicationContext
它是从类的根路径下加载配置文件推荐使用这种FileSystemXmlApplicationContext
它是从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置。
实例化时,传递的路径参数需要时绝对路径。AnnotationConfigApplicationContext
当使用注解配置容器对象时,需要使用此类来创建spring容器。它用来读取注解。
getBean()
方法的使用
getBean()
方法有两种实现方式,如下:
其中,当参数的数据类型是字符串时,表示根据Bean的id从容器中获得Bean实例,返回是Object,需要强转。当参数的数据类型是Class类型时,表示根据类型从容器中匹配Bean实例,当容器中相同类型的Bean有多个时,此方法会报错。所以当有多个相同类型的Bean时应该使用id的获取方式。
Spring配置数据源
不创建jdbc数据源的方式
Spring配置数据源可以配置bean的时候可以通过set方法进行配置。需要注意的是,属性名需要与对应的set方法对应。
配置文件中的写法:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
<property name="user" value="root"></property>
<property name="password" value="hc199854"></property>
</bean>
与手动创建c3p0数据源的代码进行对照:
//读取配置文件
ResourceBundle rb = ResourceBundle.getBundle("jdbc");
String driver = rb.getString("jdbc.driver");
String url = rb.getString("jdbc.url");
String username = rb.getString("jdbc.username");
String password = rb.getString("jdbc.password");
//创建数据源对象,设置链接参数
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
抽取jdbc配置文件的方式
上面配置数据源的方式虽然可以不用创建数据源,但是需要将value值写死。这样虽然不会导致耦合,只是我们需要修改数据库连接参数时必须到Spring配置文件中进行修改,我们希望配置数据库连接参数的部分能够独立出来,将来修改时方便。
所以就需要applicationContext.xml加载jdbc.properties配置文件获得连接信息。
需要引入context命名空间和约束路径:
- 命名空间:
xmlns:context="http://www.springframework.org/schema/context"
- 约束路径:
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
- 加载配置文件
<context:property-placeholder location="classpath:jdbc.properties"/>
整体的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: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
">
<!--加载外部的properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
</beans>
Spring注解开发
Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率。
Spring原始注解
Spring原始注解主要是替代<Bean>
的配置
注意:
使用注解进行开发时,需要在applicationContext.xml中配置组件扫描,作用是指定哪个包及其子包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法。
base-package
表示要扫描的包,同时也会扫描该包下的所有子包。
实例代码:
// <bean id="userService" class="com.itheima.service.Impl.UserServiceImpl">
//@Component("userService")
@Service("userService") //和@Component的作用是相同的,只是强调了这是service层的bean
@Scope("prototype")
public class UserServiceImpl implements UserService {
@Value("${jdbc.driver}")
private String driver;
//<property name="userDao" ref="userDao"></property>
// @Autowired //如果没有指定@Qualifier,将会按照数据类型从Spring容器中进行匹配
// @Qualifier("userDao") //按照指定id值从容器中进行匹配,但是主要此处时结合@Autowired一起使用
@Resource(name = "userDao") //相当于@Autowired加上@Qualifier
private UserDao userDao = new UserDaoImpl();
public void save() {
System.out.println(driver);
userDao.save();
}
@PostConstruct
public void init(){
System.out.println("UserServiceImpl初始化方法");
}
@PreDestroy
public void destory(){
System.out.println("UserServiceImpl销毁方法");
}
}
使用注解配置后,可以不写set方法,因为注解配置是不需要调用set方法进行对属性赋值的,而是直接对属性进行初始化。
Spring新注解
使用上面的注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下:
- 非自定义的Bean的配置:
<bean>
- 加载properties文件的配置:
<context:property-placeholder>
- 组件扫描的配置:
<context:component-scan>
- 引入其他文件:
<import>
实例代码:
@Configuration //标志该类是Spring的核心配置类
//<context:component-scan base-package="com.itheima"/>
@ComponentScan("com.itheima") //配置组件扫描
//<context:property-placeholder location="classpath:jdbc.properties"/>
@PropertySource("classpath:jdbc.properties") //加载外部的properties文件
//<import resource=""/>
@Import({DataSourceConfiguration.class}) //导入其他配置类,相当于在主配置文件中导入其他子配置文件
public class SpringCofiguration {
//<property name="driverClass" value="${jdbc.driver}"></property>
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean("dataSource") //Spring会将当前方法的返回值以指定名称存储到Spring容器中
public DataSource getDataSource() throws Exception {
//创建数据源对象,设置链接参数
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}
测试代码:
public static void main(String[] args) {
// ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
ApplicationContext app = new AnnotationConfigApplicationContext(SpringCofiguration.class);
UserService userService = app.getBean(UserService.class);
userService.save();
}
通过AnnotationConfigApplicationContext来创建ApplicationContext 。
Spring集成Junit
原始Junit测试Spring的问题:
在测试类中,每个测试方法都有以下两行代码:
Applicationcontext ac = new ClassPathXmlApplicationContext("bean.xm1");
IAccountService as = ac.getBean("accountservice",IAccountservice.class);
这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。
上述问题解决思路:
- 让SpringJunit负责创建Spring容器,但是需要将配置文件的名称告诉它。
- 将需要进行测试Bean直接在测试类中进行注入。
Spring集成Junit步骤:
- 导入spring集成Junit的坐标
- 使用@Runwith注解替换原来的运行期
- 使用@contextConfiguration指定配置文件或配置类
- 使用@Autowired注入需要测试的对象
- 创建测试方法进行测试
实例代码:
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml") //使用配置文件的方式
@ContextConfiguration(classes = {SpringCofiguration.class}) //使用全注解的方式
public class SpringJunitTest {
@Autowired
private UserService userService;
@Autowired
private DataSource dataSource;
@Test
public void test1() throws SQLException {
userService.save();
System.out.println(dataSource.getConnection());
}
}
Spring AOP
AOP简介
什么是 AOP
- AOP为Aspect Oriented Programming的缩写,意思为面向切面编程,是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
- AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
AOP的作用及其优势
- 作用:在程序运行期间,在不修改源码的情况下对方法进行功能增强。比如,在运行时将两块功能代码进行结合运行,但是在代码层面上,两块功能代码是分离,只是通过配置文件等方式将两块代码结合起来;实现了解耦。
- 优势:减少重复代码,提高开发效率,并且便于维护。
AOP的底层实现:
-
实际上,AOP的底层是通过Spring提供的的动态代理技术实现的。在运行期间,Spring通过动态代理技术动态的生成代理对象,代理对象方法执行时进行增强功能的介入,在去调用目标对象的方法,从而完成功能的增强。
-
常用的动态代理技术
JDK代理:基于接口的动态代理技术
cglib代理:基于父类的动态代理技术
JDK动态代理代码:
public class ProxyTest {
public static void main(String[] args) {
//目标对象
final Target target = new Target();
//增强对象
final Advice advice = new Advice();
//返回值就是动态生成的代理对象
TargetInterface proxy = (TargetInterface) Proxy.newProxyInstance(
target.getClass().getClassLoader(), //目标对象的类加载器
target.getClass().getInterfaces(), //目标对象的接口字节码对象数组
new InvocationHandler() {
//调用代理对象的任何方法 实质执行的都是invoke方法
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
advice.before(); //前置增强
Object invoke = method.invoke(target, args); //执行目标方法
advice.afterReturning(); //后置增强
return invoke;
}
}
);
proxy.save();
}
}
cglib动态代理代码:
public class ProxyTest {
public static void main(String[] args) {
//目标对象
final Target target = new Target();
//增强对象
final Advice advice = new Advice();
//返回值就是动态生成的代理对象 基于cglib
//1、创建增强器
Enhancer enhancer = new Enhancer();
//2、设置父类(目标)
enhancer.setSuperclass(Target.class);
//3、设置回调
enhancer.setCallback(new MethodInterceptor() {
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
advice.before(); //执行前置
Object invoke = method.invoke(target, args); // 执行目标
advice.afterReturning(); // 执行后置
return invoke;
}
});
//4、创建代理对象
Target proxy = (Target) enhancer.create();
proxy.save();
}
}
AOP相关概念:
- Target(目标对象)∶代理的目标对象
- Proxy(代理):一个类被AOP织入增强后,就产生一个结果代理类法类型的连接点
- Joinpoint(连接点)︰所谓连接点是指那些被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点。(简单说连接点就是可以被增强的方法)
- Pointcut(切入点)∶所谓切入点是指我们要对哪些Joinpoint进行拦截的定义。(简单说就是被增强的方法叫做切入点)
- Advice(通知/增强)∶所谓通知是指拦截到Joinpoint之后所要做的事情就是通知。
- Aspect(切面)∶是切入点和通知(引介)的结合。
- Weaving(织入)︰是指把增强应用到目标对象来创建新的代理对象的过程。spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入。
AOP开发需要编写的内容
- 编写核心业务代码(目标类的目标方法)
- 编写切面类,切面类中有通知(增强功能方法)
- 在配置文件中,配置织入关系,即将哪些通知与哪些连接点进行结合
AOP技术实现的内容
Spring框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。
AOP底层使用哪种代理方式
在spring中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式。
基于XML的AOP开发
开发步骤:
- 导入AOP相关坐标
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
- 创建目标接口和目标类(内部有切点)
- 创建切面类(内部有增强方法)
- 将目标类和切面类的对象创建权交给spring
- 在applicationContext.xml中配置织入关系
- 测试代码
上面步骤中的关键在于第五步配置织入关系,注意要声明命名空间,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 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 id="target" class="com.itheima.aop.Target"></bean>
<!--切面对象-->
<bean id="myAspect" class="com.itheima.aop.MyAspect"></bean>
<!--配置织入:告诉spring框架哪些方法(切点)需要进行哪些增强(前置、后置)-->
<aop:config>
<!--声明切面-->
<aop:aspect ref="myAspect">
<!--切面=切点+通知-->
<aop:before method="before" pointcut="execution(public void com.itheima.aop.Target.save())"></aop:before>
</aop:aspect>
</aop:config>
</beans>
切点表达式的写法
表达式语法:
- 访问修饰符可以省略
- 返回值类型、包名、类名、方法名可以使用星号*代表任意
- 参数列表可以使用两个点
..
表示任意个数,任意类型的参数列表 - 包名与类名之间一个点.代表当前包下的类,两个点
..
表示当前包及其子包下的类
常见的例子:
通知的种类:
通知的配置语法:
共五类通知:
案例:
切面类代码:
package com.itheima.aop;
import org.aspectj.lang.ProceedingJoinPoint;
public class MyAspect {
public void before(){
System.out.println("前置增强。。。。。。。。。。。。。");
}
public void afterReturning(){
System.out.println("后置增强。。。。。。。。。。。。。");
}
//Proceeding JoinPoint:正在执行的连接点
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前增强。。。。。。。。。");
Object proceed = pjp.proceed(); //切点方法
System.out.println("环绕后增强。。。。。。。。。");
return proceed;
}
public void afterThrowing(){
System.out.println("异常抛出增强。。。。。。。。。。。。。");
}
public void after(){
System.out.println("最终增强。。。。。。。。。。。。。");
}
}
配置文件代码:
<!--目标对象-->
<bean id="target" class="com.itheima.aop.Target"></bean>
<!--切面对象-->
<bean id="myAspect" class="com.itheima.aop.MyAspect"></bean>
<!--配置织入:告诉spring框架哪些方法(切点)需要进行哪些增强(前置、后置)-->
<aop:config>
<!--声明切面-->
<aop:aspect ref="myAspect">
<!--切面=切点+通知-->
<!--<aop:before method="before" pointcut="execution(public void com.itheima.aop.Target.save())"></aop:before>-->
<!--<aop:after-returning method="afterReturning" pointcut="execution(public void com.itheima.aop.Target.save())"></aop:after>-->
<aop:around method="around" pointcut="execution(public void com.itheima.aop.Target.save())"></aop:around>
<aop:after-throwing method="afterThrowing" pointcut="execution(public void com.itheima.aop.Target.save())"></aop:after-throwing>
<aop:after method="after" pointcut="execution(public void com.itheima.aop.Target.save())"></aop:after>
</aop:aspect>
</aop:config>
切点表达式的抽取
当多个增强的切点表达式相同时,可以将切点表达式进行抽取,在增强中使用pointcut-ref属性代替pointcut属性来引用抽取后的切点表达式。
这样做的好处是:当需要修改切点表达式时不用修改多行代码,只需要修改一行 代码即可。
模板:
代码实现:
<!--目标对象-->
<bean id="target" class="com.itheima.aop.Target"></bean>
<!--切面对象-->
<bean id="myAspect" class="com.itheima.aop.MyAspect"></bean>
<!--配置织入:告诉spring框架哪些方法(切点)需要进行哪些增强(前置、后置)-->
<aop:config>
<!--声明切面-->
<aop:aspect ref="myAspect">
<!--抽取切点表达式-->
<aop:pointcut id="myPointcut" expression="execution(* com.itheima.aop.*.*(..))"></aop:pointcut>
<!--切面=切点+通知-->
<!--<aop:before method="before" pointcut="execution(public void com.itheima.aop.Target.save())"></aop:before>-->
<!--<aop:after-returning method="afterReturning" pointcut="execution(public void com.itheima.aop.Target.save())"></aop:after>-->
<!--<aop:around method="around" pointcut="execution(public void com.itheima.aop.Target.save())"></aop:around>
<aop:after-throwing method="afterThrowing" pointcut="execution(public void com.itheima.aop.Target.save())"></aop:after-throwing>
<aop:after method="after" pointcut="execution(public void com.itheima.aop.Target.save())"></aop:after>-->
<aop:around method="around" pointcut-ref="myPointcut"></aop:around>
<aop:after method="after" pointcut-ref="myPointcut"></aop:after>
</aop:aspect>
</aop:config>
基于注解的AOP开发
开发步骤:
- 创建目标接口和目标类(内部有切点)
- 创建切面类(内部有增强方法)
- 将目标类和切面类的对象创建权交给spring
- 在切面类中使用注解配置织入关系
- 在配置文件中开启组件扫描和AOP的自动代理
- 测试
案例代码如下:
目标类:
@Component("target")
public class Target implements TargetInterface {
public void save() {
// int i = 1/0;
System.out.println("running......");
}
}
切面类:
@Component("myAspect")
@Aspect //标注当前MyAspect是一个切面类
public class MyAspect {
//配置前置通知
@Before(value = "execution(* com.itheima.anno.*.*(..))")
public void before(){
System.out.println("前置增强。。。。。。。。。。。。。");
}
public void afterReturning(){
System.out.println("后置增强。。。。。。。。。。。。。");
}
//Proceeding JoinPoint:正在执行的连接点
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前增强。。。。。。。。。");
Object proceed = pjp.proceed(); //切点方法
System.out.println("环绕后增强。。。。。。。。。");
return proceed;
}
public void afterThrowing(){
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"
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
">
<!--组件扫描-->
<context:component-scan base-package="com.itheima.anno"/>
<!--aop自动代理-->
<aop:aspectj-autoproxy/>
</beans>
注意一定要添加组件扫描和动态代理
注解通知的类型
通知的配置语法:
共五种通知类型:
切点表达式的抽取:
同xml配置aop一样,我们可以将切点表达式抽取。抽取方式是在切面内定义方法,在该方法上使用@Pointcut注解定义切点表达式,然后在在增强注解中进行引用。具体如下:
案例代码:
@Component("myAspect")
@Aspect //标注当前MyAspect是一个切面类
public class MyAspect {
//配置前置通知
// @Before(value = "execution(* com.itheima.anno.*.*(..))")
@Before("pointcut()")
public void before(){
System.out.println("前置增强。。。。。。。。。。。。。");
}
public void afterReturning(){
System.out.println("后置增强。。。。。。。。。。。。。");
}
// @Around("execution(* com.itheima.anno.*.*(..))")
@Around("pointcut()")
//Proceeding JoinPoint:正在执行的连接点
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前增强。。。。。。。。。");
Object proceed = pjp.proceed(); //切点方法
System.out.println("环绕后增强。。。。。。。。。");
return proceed;
}
public void afterThrowing(){
System.out.println("异常抛出增强。。。。。。。。。。。。。");
}
// @After("execution(* com.itheima.anno.*.*(..))")
@After("pointcut()")
public void after(){
System.out.println("最终增强。。。。。。。。。。。。。");
}
//定义切点表达式, 这个方法的作用是用来定义切点的,所以方法体不需要写东西,这个方法的存在是为了写注解
@Pointcut("execution(* com.itheima.anno.*.*(..))")
public void pointcut(){ }
}
JdbcTemplate基本使用
JdbcTemplate简介:
它是spring框架中提供的一个对象,是对原始繁琐的JdbcAPI对象的简单封装。spring框架为我们提供了很多的操作模板类。例如:操作关系型数据的JdbcTemplate和HibernateTemplate,操作nosql数据库的RedisTemplate,操作消息队列的JmsTemplate等等。
JdbcTemplate开发步骤:
- 导入spring-jdbc和spring-tx坐标
- 创建数据库表和实体
- 创建JdbcTemplate对象
- 执行数据库操作
Spring产生JdbcTemplate对象
我们可以将JdbcTemplate的创建权交给Spring,将数据源DataSource的创建权也交给Spring,在Spring容器内部将数据源DataSource注入到JdbcTemplate模版对象中,配置如下:
更常用的方式是将jdbc配置文件进行抽取:
注意设置命名空间
<?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/context/spring-context.xsd
">
<!--加载jdbc.properties-->
<context:property-placeholder location="classpath: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>
<!--jdbc模板对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
测试代码:
@Test
//测试spring产生jdbcTemplate对象
public void test2() throws Exception {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jdbcTemplate = app.getBean(JdbcTemplate.class);
jdbcTemplate.update("insert INTO account VALUES (?,?)", "tom", 5000);
}
JdbcTemplate的常用操作
package cn.itcast.jdbctemplate;
import cn.itcast.domain.Emp;
import cn.itcast.utils.JDBCUtils;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
public class JdbcTemplateDemo2 {
//1. 获取JDBCTemplate对象
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
/**
* 1. 修改1号数据的 salary 为 10000
*/
@Test
public void test1(){
//2. 定义sql
String sql = "update emp set salary = 10000 where id = 1001";
//3. 执行sql
int count = template.update(sql);
System.out.println(count);
}
/**
* 2. 添加一条记录
*/
@Test
public void test2(){
String sql = "insert into emp(id,ename,dept_id) values(?,?,?)";
int count = template.update(sql, 1015, "郭靖", 10);
System.out.println(count);
}
/**
* 3.删除刚才添加的记录
*/
@Test
public void test3(){
String sql = "delete from emp where id = ?";
int count = template.update(sql, 1015);
System.out.println(count);
}
/**
* 4.查询id为1001的记录,将其封装为Map集合
* 注意:这个方法查询的结果集长度只能是1
*/
@Test
public void test4(){
String sql = "select * from emp where id = ? or id = ?";
Map<String, Object> map = template.queryForMap(sql, 1001,1002);
System.out.println(map);
//{id=1001, ename=孙悟空, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20}
}
/**
* 5. 查询所有记录,将其封装为List
*/
@Test
public void test5(){
String sql = "select * from emp";
List<Map<String, Object>> list = template.queryForList(sql);
for (Map<String, Object> stringObjectMap : list) {
System.out.println(stringObjectMap);
}
}
/**
* 6. 查询所有记录,将其封装为Emp对象的List集合
*/
@Test
public void test6(){
String sql = "select * from emp";
List<Emp> list = template.query(sql, new RowMapper<Emp>() {
@Override
public Emp mapRow(ResultSet rs, int i) throws SQLException {
Emp emp = new Emp();
int id = rs.getInt("id");
String ename = rs.getString("ename");
int job_id = rs.getInt("job_id");
int mgr = rs.getInt("mgr");
Date joindate = rs.getDate("joindate");
double salary = rs.getDouble("salary");
double bonus = rs.getDouble("bonus");
int dept_id = rs.getInt("dept_id");
emp.setId(id);
emp.setEname(ename);
emp.setJob_id(job_id);
emp.setMgr(mgr);
emp.setJoindate(joindate);
emp.setSalary(salary);
emp.setBonus(bonus);
emp.setDept_id(dept_id);
return emp;
}
});
for (Emp emp : list) {
System.out.println(emp);
}
}
/**
* 6. 查询所有记录,将其封装为Emp对象的List集合
*/
@Test
public void test6_2(){
String sql = "select * from emp";
List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
for (Emp emp : list) {
System.out.println(emp);
}
}
/**
* 7. 查询总记录数
*/
@Test
public void test7(){
String sql = "select count(id) from emp";
Long total = template.queryForObject(sql, Long.class);
System.out.println(total);
}
}
Spring的事务控制
编程式事务控制
编程式事务控制相关对象
-
PlatformTransactionManager:
PlatformTransactionManager接口是spring 的事务管理器,它里面提供了我们常用的操作事务的方法。
注意:
PlatformTransactionManager是接口类型,不同的Dao层技术则有不同的实现类,例如:
Dao层技术是jdbc或mybatis时:org.springframework.jdbc.datasource.DataSourceTransactionManager
Dao层技术是hibernate时:org.springframework.orm.hibernate5.HibernateTransactionManager
-
TransactionDefinition
TransactionDefinition是事务的定义信息对象,里面有如下方法:
说明:
事务的隔离级别:设置隔离级别,可以解决事务并发产生的问题,如脏读、不可重复读和虚读。隔离级别有以下几种:
Spring事务隔离级别比数据库事务隔离级别多一个default
-
DEFAULT (默认)
这是一个PlatfromTransactionManager默认的隔离级别,使用数据库默认的事务隔离级别。另外四个与JDBC的隔离级别相对应。 -
READ_UNCOMMITTED (读未提交)
这是事务最低的隔离级别,它允许另外一个事务可以看到这个事务未提交的数据。这种隔离级别会产生脏读,不可重复读和幻像读。 -
READ_COMMITTED (读已提交)
保证一个事务修改的数据提交后才能被另外一个事务读取,另外一个事务不能读取该事务未提交的数据。这种事务隔离级别可以避免脏读出现,但是可能会出现不可重复读和幻像读。 -
REPEATABLE_READ (可重复读)
这种事务隔离级别可以防止脏读、不可重复读,但是可能出现幻像读。它除了保证一个事务不能读取另一个事务未提交的数据外,还保证了不可重复读。 -
SERIALIZABLE(串行化)
这是花费最高代价但是最可靠的事务隔离级别,事务被处理为顺序执行。除了防止脏读、不可重复读外,还避免了幻像读。事件的传播行为:是为了解决业务方法调用业务方法时事务统一性的问题,例如:A业务调用了B业务的方法,而且A和B都进行了事务控制,这时有可能会出现事务重复等问题。传播行为的种类如下:
- TransactionStatus
TransactionStatus接口提供的是事务具体的运行状态,方法介绍如下。
基于xml的声明式事务控制
什么是声明式事务控制:
Spring的声明式事务顾名思义就是采用声明的方式来处理事务。这里所说的声明,就是指在配置文件中声明。
声明式事务处理的作用:
-
事务管理不侵入开发的组件。具体来说,业务逻辑对象就不会意识到正在事务管理之中,事实上也应该如此,因为事务管理是属于系统层面的服务,而不是业务逻辑的一部分,果想要改变事务管理策划的话,也只需要在定义文件中重新配置即可。
也就是说,将业务代码和事务控制分离,通过配置的方式进行松耦合;其实这也是一种AOP思想。 -
在不需要事务管理的时候,只要在设定文件上修改一下,即可移去事务管理服务,无需改变代码重新编译 ,这样维护起来极其方便。
注意: Spring声明式事务控制底层就是AOP。
声明式事务控制的实现:
由于 Spring声明式事务控制底层就是AOP思想,所以首先应该明确三个点:
- 谁是切点?
- 谁是通知?
- 配置切面?
切点方法的事务参数的配置:
其中,tx:method代表切点方法的事务参数的配置,例如:
name
:切点方法名称isolation
:事务的隔离级别propogation
:事务的传播行为timeout
:超时时间read-only
:是否只读
案例实现:
service层代码:
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
public void transfer(String outMan, String inMan, double money) {
accountDao.out(outMan, money);
int i = 1/0;
accountDao.in(inMan, money);
}
}
测试代码:
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = app.getBean(AccountService.class);
accountService.transfer("tom", "lucy", 500);
}
声明代码的实现:
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
">
<!--数据源对象-->
<bean id="dataSource" 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="hc199854"/>
</bean>
<!--jdbc模板对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<!--目标对象 内部的方法就是切点-->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--配置平台事务管理器-->
<!--注意不同的dao层技术使用不同的管理器-->
<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="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="save" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="findAll" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
<!--表示容易方法, 这些方法(事务)都使用默认值-->
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!--配置事务的aop织入-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:advisor>
</aop:config>
</beans>
注意设置命名空间
基于注解的声明式事务控制
注解配置声明式事务控制解析:
- 使用@Transactional在需要进行事务控制的类或是方法上修饰,注解可用的属性同xml配置方式,例如隔离级别、传播行为等。
- 注解使用在类上,那么该类下的所有方法都使用同一套注解参数配置。
- 使用在方法上,不同的方法可以采用不同的事务参数配置。Xml配置文件中要开启事务的注解驱动
<tx:annotation-driven/>
将上面的xml案例修改为注解方式的案例:
service层代码:
@Service("accountService")
@Transactional(isolation = Isolation.REPEATABLE_READ) //代表以下所有的方法都使用这个事务,如果冲突使用就近原则
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
public void transfer(String outMan, String inMan, double money) {
accountDao.out(outMan, money);
int i = 1/0;
accountDao.in(inMan, money);
}
}
配置文件代码:
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:coutext="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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
<!--组件扫描-->
<coutext:component-scan base-package="com.itheima"/>
<!--数据源对象-->
<bean id="dataSource" 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="hc199854"/>
</bean>
<!--jdbc模板对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置平台事务管理器-->
<!--注意不同的dao层技术使用不同的管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--事务的注解驱动-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
注意:一定不要忘了在配置文件中写注解驱动和组件扫描。
注解声明式事务控制的配置要点总结:
- 平台事务管理器配置(xml方式)
- 事务通知的配置(@Transactional注解配置)
- 事务注解驱动的配置
<tx: annotation-driven/>