文章目录
一、Spring简介
1.1Spring是什么
Spring是分层的Java SE/EE应用full-stack轻量级开源框架,以IOC(InverseOfControl:反转控制)和AOP(ApesOrientedProgramming:面向切面编程)为内核。
提供了展现层SpringMVC和持久层SpringJDBCTemplate以及业务层事务管理等众多的企业级应用技术,还能整合开源世界众多著名的第三方框架和类库,逐渐成为使用最多的JavaEE企业应用开源框架。
1.2Spring发展历程
1997年,IBM提出了EJB的思想
1998年,SUN指定开发标准规范EJB1.0
1999年.EJB1.1发布
2001年,EJB2.0发布
2003年,EJB2.1发布
2006年,EJB3.0发布
Rod Johnson(Spring之父)
ExpertOne-to-One J2EE Design and Development(2002)
阐述了J2EE使用EJB开发设计的优点及解决方案
ExpertOne-to-One J2EE Development without EJB(2004)
阐述了J2EE开发不使用EJB的解决方式(Spring雏形)
1.3Spring的优势
- 方便解耦,简化开发
通过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技术的最佳实践的范例。
1.4Spring的体系结构
二、Spring快速入门
2.1Spring程序的开发步骤
-
导入Spring开发的基本包坐标
<!--Spring开发的基本包坐标--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.5.RELEASE</version> </dependency>
-
编写Dao接口和实现类
public class StudnetDaoImpl implements StudentDao { public void save() { System.out.println("save running..."); } }
-
创建Spring核心配置文件
<?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"> </beans>
-
在Spring配置文件中配置UserDaoImpl
<?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="studentDao" class="com.d105.dao.impl.StudnetDaoImpl"/> </beans>
-
使用Spring的API获得Bean实例
public class StudentDaoDemo { public static void main(String[] args) { ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml"); StudentDao studentDao =(StudentDao) app.getBean("studentDao"); studentDao.save(); } }
2.2知识要点
-
导入坐标
-
创建Bean
-
创建applicationContext.xml
-
在配置文件中进行配置
-
创建ApplicationContext对象getBean
3.1Bean标签基本配置
用于配置对象交由Spring来创建
默认情况下它调用的类中的无参构造函数。如果没有无参构造函数则不能创建成功。
基本属性:
-
Id:Bean实例在Spring容器中的唯一标识
-
class:Bean的全限定名称
3.2Bean标签范围配置
<bean id="studentDao" class="com.d105.dao.impl.StudnetDaoImpl" scope="singleton"/>
scope:指对象的作用范围。取值如下:
- 当scope的取值为singleton时
Bean的实例化个数:1个
Bean的实例化时机:当Spring核心文件被加载时,实例化配置的Bean实例
Bean的生命周期:
-
对象创建:当应用加载,创建容器时,对象就被创建了
-
对象运行:只要容器在,对象一直活着
-
对象销毁:当应用卸载,销毁容器时,对象被销毁了
<bean id="studentDao" class="com.d105.dao.impl.StudnetDaoImpl" scope="singleton"/>
public class StudentDaoDemo { public static void main(String[] args) { ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml"); StudentDao studentDao =(StudentDao) app.getBean("studentDao"); StudentDao studentDao1 =(StudentDao) app.getBean("studentDao"); System.out.println(studentDao); System.out.println(studentDao1); } }
输出结果
com.d105.dao.impl.StudnetDaoImpl@3e6fa38a com.d105.dao.impl.StudnetDaoImpl@3e6fa38a
- 当scope的取值为prototype时
Bean的实例化个数:多个
Bean的实例化时机:当调用getBean()方法时实例化Bean
-
对象创建:当使用对象时创建新的对象实例
-
对象运行:只需要在使用中,就一直活着
-
对象销毁:当对象长时间不用,被Java的垃圾回收器收回了
<bean id="studentDao" class="com.d105.dao.impl.StudnetDaoImpl" scope="prototype"/>
public class StudentDaoDemo { public static void main(String[] args) { ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml"); StudentDao studentDao =(StudentDao) app.getBean("studentDao"); StudentDao studentDao1 =(StudentDao) app.getBean("studentDao"); System.out.println(studentDao); System.out.println(studentDao1); } }
输出结果
com.d105.dao.impl.StudnetDaoImpl@3ffc5af1 com.d105.dao.impl.StudnetDaoImpl@5e5792a0
3.3Bean生命周期配置
-
init-method:指定类中的初始化方法名称
-
destroy-method:指定类中销毁方法名称
public class StudnetDaoImpl implements StudentDao { public void save() { System.out.println("save running..."); } public void init(){ System.out.println("初始化"); } public void destroy(){ System.out.println("销毁"); } }
<bean id="studentDao" class="com.d105.dao.impl.StudnetDaoImpl" init-method="init" destroy-method="destroy"/>
public class StudentDaoDemo { public static void main(String[] args) { ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml"); StudentDao studentDao =(StudentDao) app.getBean("studentDao"); } }
输出结果
初始化 销毁
3.4Bean实例化的三种方式
-
无参构造方法实例化
-
工厂静态方法实例化
public class StaticFactory { public static StudentDao getStudnetDao(){ return new StudnetDaoImpl(); } }
<bean id="studentDao" class="com.d105.factory.StaticFactory" factory-method="getStudnetDao"/>
public class StudentDaoDemo { public static void main(String[] args) { ClassPathXmlApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml"); StudentDao studentDao =(StudentDao) app.getBean("studentDao"); System.out.println(studentDao); } }
输出结果
com.d105.dao.impl.StudnetDaoImpl@204f30ec
-
工厂实例方法实例化
public class DynamicFactory { public StudentDao getStudnetDao(){ return new StudnetDaoImpl(); } }
<bean id="factoy" class="com.d105.factory.DynamicFactory"/> <bean id="studentDao" factory-bean="factoy" factory-method="getStudnetDao"/>
public class StudentDaoDemo { public static void main(String[] args) { ClassPathXmlApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml"); StudentDao studentDao =(StudentDao) app.getBean("studentDao"); System.out.println(studentDao); } }
输出结果
com.d105.dao.impl.StudnetDaoImpl@204f30ec
3.5Bean的依赖注入分析
目前UserService实例和UserDao实例都存在与Spring容器中,当前的做法是在容器外部获得UserService实例和UserDao实例,然后在程序中进行执行结合
public class StudentServiceImpl implements StudentService {
@Override
public void save() {
ClassPathXmlApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
StudentDao studentDao =(StudentDao) app.getBean("studentDao");
studentDao.save();
}
}
<bean id="studentDao" class="com.d105.dao.impl.StudnetDaoImpl"/>
<bean id="studentService" class="com.d105.service.StudentServiceImpl"/>
public class StudentController {
public static void main(String[] args) {
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
StudentService service=(StudentServiceImpl)app.getBean("studentService");
service.save();
}
}
输出结果
save running...
因为UserService和UserDao都在Spring容器中,而最终程序直接使用的是UserService,所以可以在Spring容器中,将UserDao设置到UserService内部。
3.6Bean的依赖注入概念
依赖注入(Dependency Injecttion):它是Spring框架的核心IOC的具体实现。
在编写程序时,通过控制反转,把对象的创建交给Spring,但是代码中不可能出现没有依赖的情况。
IOC解耦只是降低他们的依赖关系。但不会消除。例如:业务层仍会调用持久层的方法。
那这种业务层和持久层的依赖关系,在使用Spring之后,就让Spring来维护了。
简单的说,就是坐等框架把持久层对象传入业务层,而不用我们自己去获取。
3.7Bean的依赖注入方式
-
构造方法
-
set方法
- set方法注入
public class StudentServiceImpl implements StudentService {
StudentDao studentDao;
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
public void save() {
studentDao.save();
}
}
<bean id="studnetDao" class="com.d105.dao.impl.StudnetDaoImpl"/>
<bean id="studentService" class="com.d105.service.StudentServiceImpl">
<!--name:setStudentDao()方法后面的即studentDao(大写变小写)-->
<!--ref:配置Dao层的bean-->
<property name="studentDao" ref="studnetDao"/>
</bean>
public class StudentController {
public static void main(String[] args) {
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
StudentService service=(StudentServiceImpl)app.getBean("studentService");
service.save();
}
}
输出结果
save running...
set方法有一个简便的方法:
p命名空间注入本质也是set方法注入,但此时上述的set方法注入更加方便,主要体现在配置文件中,如下:
-
首先,需要引入P命名空间:
xmlns:p="http://www.springframework.org/schema/p"
-
其次,需要修改注入方式
<bean id="studnetDao" class="com.d105.dao.impl.StudnetDaoImpl"/> <bean id="studentService" class="com.d105.service.StudentServiceImpl" p:studentDao-ref="studnetDao"/>
3.8Bean的依赖注入的数据类型
上面的操作,都是注入的引用Bean,除了对象的引用可以注入,普通数据类型,集合等都可以在容器中进行注入。
注入数据的三种数据类型
-
普通数据类型
public class StudnetDaoImpl implements StudentDao { private int sno; private String snaem; public int getSno() { return sno; } public void setSno(int sno) { this.sno = sno; } public String getSnaem() { return snaem; } public void setSnaem(String snaem) { this.snaem = snaem; } public void save() { System.out.println(sno+"====="+snaem); System.out.println("save running..."); } }
<bean id="studnetDao" class="com.d105.dao.impl.StudnetDaoImpl"> <property name="sno" value="301"/> <property name="snaem" value="威哥"/> </bean>
public class StudentDaoDemo { public static void main(String[] args) { ClassPathXmlApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml"); StudentDao studentDao =(StudentDao) app.getBean("studnetDao"); studentDao.save(); } }
输出结果
301=====威哥 save running...
-
引用数据类型
前面所用的对象注入类型就是引用数据类型
-
集合数据类型
public class StudnetDaoImpl implements StudentDao { private List<String> list; //User里有名字(name)和地址(addr) private Map<String, User> userMap; private Properties properties; public void setList(List<String> list) { this.list = list; } public void setUserMap(Map<String, User> userMap) { this.userMap = userMap; } public void setProperties(Properties properties) { this.properties = properties; } public void save() { System.out.println(list); System.out.println(userMap); System.out.println(properties); System.out.println("save running..."); } }
<bean id="studnetDao" class="com.d105.dao.impl.StudnetDaoImpl"> <property name="list"> <list> <value>aaa</value> <value>bbb</value> <value>ccc</value> </list> </property> <property name="userMap"> <map> <entry key="301" value-ref="user1"/> <entry key="仔仔" value-ref="user2"/> </map> </property> <property name="properties"> <props> <prop key="301">威哥</prop> <prop key="仔仔">华仔</prop> </props> </property> </bean> <bean id="user1" class="com.d105.entity.User"> <property name="naem" value="威哥"/> <property name="addr" value="贺州"/> </bean> <bean id="user2" class="com.d105.entity.User"> <property name="naem" value="华仔"/> <property name="addr" value="玉林"/> </bean>
public class StudentDaoDemo { public static void main(String[] args) { ClassPathXmlApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml"); StudentDao studentDao =(StudentDao) app.getBean("studnetDao"); studentDao.save(); } }
输出结果
[aaa, bbb, ccc] {301=User{naem='威哥', addr='贺州'}, 仔仔=User{naem='华仔', addr='玉林'}} {仔仔=华仔, 301=威哥} save running...
3.9引入其他配置文件(分模块开发)
实际开发中,Spring的配置内容非常多,这就导致Spring配置很繁杂且体积很大,所以,可以将部分配置拆解到其他配置文件中,而在Spring主配置文件通过import标签进行加载。
<import resource="applicationContext-xxx.xml"/>
3.10知识要点
Spring的重点配置
标签
Id属性:在容器中bean实例的唯一标识,不允许重置
class属性:要实例化的bean的全限定名
scope属性:bean的作用范围,常用是singleton(默认)和prototype
标签:属性注入
name属性:属性名称
value属性:注入的普通属性值
ref属性:注入的对象引用值
标签
标签
标签(构造方法)
标签:导入其他的Spring的分文件
四、Spring相关的API
4.1ApplicationContext的继承体系
applicationContext:接口类型,代表应用上下文,可以通过其他势力获得Spring容器中的bean对象
4.2applicationContext的实现类
-
ClassPathXmlApplictionContext
它是从类的根路径下加载配置文件推荐使用这种
-
FileSystemXMLApplicationContext
它是从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置
-
AnnotationConfigApplicationContext
当使用注解配置容器对象时,需要使用此类来创建Spring容器。它用来读取注解。
4.3getBean()方法使用
public class StudentDaoDemo {
public static void main(String[] args) {
ClassPathXmlApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
// StudentDao studentDao =(StudentDao) app.getBean("studnetDao");
StudentDao studentDao = app.getBean(StudentDao.class);
studentDao.save();
}
}
输出结果
[aaa, bbb, ccc]
{301=User{naem='威哥', addr='贺州'}, 仔仔=User{naem='华仔', addr='玉林'}}
{仔仔=华仔, 301=威哥}
save running...
其中,当参数的数据类型是字符串时,表示根据Bean的ID从从容器中获得实例,返回是Object,需要强转。当参数的数据类型是Class类型时,表示根据类型从容器中匹配Bean实例,当容器中相同类型的Bean有多个时,则次方法会报错。
4.4知识要点
Spring的重点API
五、Spring配置数据源
5.1数据源(连接池)的作用
-
数据源(连接池)是提高程序性能如出现的
-
事先实例化数据源,初始化部分连接资源
-
使用连接资源时从数据源中获取
-
使用完毕后将连接资源归还给数据源
常见的数据源(连接池):DBCP、C3P0、BoneCP、Druid等
5.2数据源的开发步骤
-
导入数据源的坐标和数据驱动坐标
-
创建数据源对象
-
设置数据源的基本连接数据
-
使用数据源获取连接资源和归还连接资源
实例1:
<dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency>
@Test //测试手动创建 c3p0数据源 public void test1() throws Exception{ //创建创建数据源对象 ComboPooledDataSource dataSource = new ComboPooledDataSource(); //设置数据源的基本连接数据 dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/d105?serverTimezone=UTC"); dataSource.setUser("root"); dataSource.setPassword("123456"); Connection connection = dataSource.getConnection(); System.out.println(connection); //归还资源源 connection.close(); }
输出结果
com.mchange.v2.c3p0.impl.NewProxyConnection@2acf57e3
实例2:
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency>
@Test //测试手动创建 druid数据源 public void test2()throws Exception{ //创建创建数据源对象 DruidDataSource druidDataSource = new DruidDataSource(); //设置数据源的基本连接数据 druidDataSource.setDriverClassName("com.mysql.jdbc.Driver"); druidDataSource.setUrl("jdbc:mysql://localhost:3306/d105?serverTimezone=UTC"); druidDataSource.setUsername("root"); druidDataSource.setPassword("123456"); DruidPooledConnection connection = druidDataSource.getConnection(); System.out.println("druid:"+connection); druidDataSource.close(); }
输出结果
druid:com.mysql.jdbc.JDBC4Connection@649d209a
实例3(加载properties):
@Test //测试手动创建 c3p0数据源(加载properties文件) public void test3() throws Exception { ResourceBundle rb = ResourceBundle.getBundle("jdbc"); String driver = rb.getString("jdbc.driver"); String url = rb.getString("jdbc.url"); String usernaem = rb.getString("jdbc.username"); String password = rb.getString("jdbc.password"); //创建创建数据源对象 ComboPooledDataSource dataSource = new ComboPooledDataSource(); //设置数据源的基本连接数据 dataSource.setDriverClass(driver); dataSource.setJdbcUrl(url); dataSource.setUser(usernaem); dataSource.setPassword(password); Connection connection = dataSource.getConnection(); System.out.println("c3p0(properties):"+connection); //归还资源源 connection.close(); }
输出结果
c3p0(properties):com.mchange.v2.c3p0.impl.NewProxyConnection@506e6d5e
5.3Spring配置数据源
可以将DataSource的创建权交由Spring容器去完成
Spring配置数据源(c3p0):
<bean id="dataSources" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/d105?serverTimezone=UTC"/>
<property name="user" value="root"/>
<property name="Password" value="123456"/>
</bean>
@Test
//Spring配置数据源
public void test4() throws Exception{
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = app.getBean(DataSource.class);
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
输出结果
com.mchange.v2.c3p0.impl.NewProxyConnection@40e6dfe1
Spring配置数据源(druid):
<bean id="dataSources1" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/d105?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
@Test
//Spring配置数据源 druid数据源
public void test5()throws Exception{
//创建创建数据源对象
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
DruidDataSource druidDataSource = app.getBean(DruidDataSource.class);
DruidPooledConnection connection = druidDataSource.getConnection();
System.out.println("druid:"+connection);
druidDataSource.close();
}
输出结果
druid:com.mysql.jdbc.JDBC4Connection@223f3642
5.4Spring加载properties文件
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="jdbc.properties"/>
<bean id="dataSources1" 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>
六、Spring注解开发
6.1Spring原始注解
Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率。
Spring原始注解主要是代替的配置
注解 | 说明 |
---|---|
@Component | 使用在类上用于实例Bean |
@Controller | 使用web层类上用于实例化Bean |
@Service | 使用service层类上用于实例化Bean |
@Repository | 使用在dao层上用于实例化Bean |
@Autowired | 使用在字段上用于根据类型依赖注入 |
@Qualifier | 结合@Autowired一起使用用于根据名称进行依赖注入 |
@Resource | 相当于@Autowired+@Qualifer,安卓名称进行注入 |
@Value | 注入普通属性 |
@Scope | 标注Bean的作用范围 |
@PostConstruct | 使用在方法上标注该方法是Bean的初始化方法 |
@PreDestroy | 使用在方法上标注该方法是Bean的销毁方法 |
注意:
使用注解进行开发时,需要在applicationContext.xml中配置组件扫描,作用是指哪个包及其子包下的Bean需要进行扫描以使用注解配置的类、字段和方法。
<context:component-scan base-package="com.d105"/>
实例:
<!--注意这两个顺序不能反着写-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<context:component-scan base-package="com.d105"/>
//<bean id="studnetDao" class="com.d105.dao.impl.StudnetDaoImpl"/>
@Component("studentDao")//@Repository("studentDao")
public class StudnetDaoImpl implements StudentDao {
private StudentDao studentDao;
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
public void save() {
System.out.println("save running...");
}
}
//<bean id="studentService" class="com.d105.service.StudentServiceImpl"></bean>
@Component("studentService")//@Service("studentService")
@Service("studentService")
public class StudentServiceImpl implements StudentService {
@Value("${jdbc.driver}")
private String driver;
//<property name="studentDao" ref="studnetDao"/>
// @Autowired//按照数据类型从Spring容器中进行匹配的
// @Qualifier("studentDao")//是按照id值从容器中进行匹配的 但是注意此处 @Qualifier结合@Autowired一起使用
@Resource(name="studentDao")//相当于@Autowired+@Qualifer
StudentDao studentDao;
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
public void save(){
System.out.println(driver);
studentDao.save();
}
}
public class StudentController {
public static void main(String[] args) {
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
StudentService service=(StudentServiceImpl)app.getBean("studentService");
service.save();
}
}
输出结果
com.mysql.jdbc.Driver
save running...
6.2Spring新注解
使用上面的注解还不能全部替代xml配置文件,还需要使用注解的配置如下:
- 非自定义的Bean的配置:
- 加载properties文件的配置:context:property-placeholder
- 组件扫描的配置:context:component-scan
- 引入其他文件:
注解 | 说明 |
---|---|
@Configuration | 用于指定当前类是一个Spring配置类,当创建容器时会从该类上加载注解 |
@ComponentScan | 用于指定Spring在初始化容器时要扫描的包。作用和在Spring中的xml配置文件中的<context:component-scan base-package=“com.d105”/>一样 |
@Bean | 使用在方法上,标注将该方法的返回值存储到Spring容器中 |
@PropertieSource | 用于加载properties文件中的配置 |
@import | 用于导入其他配置类 |
//标志这个类是Spring的核心配置类
@org.springframework.context.annotation.Configuration
//<context:component-scan base-package="com.d105"/>
@ComponentScan("com.d105")
//<context:property-placeholder location="classpath:jdbc.properties"/>
@PropertySource("classpath:jdbc.properties")
//<import resource="applicationContext-xxx.xml"/>
//@Import({Configuration.class})
public class Configuration {
@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")
public DataSource getDataSource() throws Exception{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
//设置数据源的基本连接数据
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}
@Test
public void test6()throws Exception{
ApplicationContext app = new AnnotationConfigApplicationContext(Configuration.class);
DataSource dataSource = app.getBean(DataSource.class);
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
输出结果
com.mchange.v2.c3p0.impl.NewProxyConnection@31190526
七、Spring集成Junit测试
7.1原始Junit测试Spring的问题
在测试类中,每个测试方法都有以下两行代码
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = app.getBean(DataSource.class);
这两行代码的作用是获取容器,如果不写的话直接提示空指针异常,所以不能轻易删掉。
7.2上述问题解决思路
-
让SpringJunit负责创建Spring容器。但是需要将配置文件的名称告诉它
-
将需要进行测试Bean直接在测试类中进行注入
7.3Spring集成Junit步骤
- 导入Spring集成Junit的坐标
- 使用@Runwith注解替换原来的运行期
- 使用@ContextConfiguration指定配置文件或配置类
- 使用@Autowired注入需要测试的对象
- 创建测试方法进行测试
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")
@ContextConfiguration(classes = {Configuration.class})
public class SpringJunitTest {
@Autowired
@Qualifier("dataSource")
private DataSource dataSource;
@Test
public void test1() throws SQLException {
System.out.println(dataSource.getConnection());
}
}
输出结果
com.mchange.v2.c3p0.impl.NewProxyConnection@548e6d58
八、Spring的AOP简介
8.1什么是AOP
AOP是Aspect Oriented Programming的缩写,意思为面向切面编程,是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
AOP是OOP的延续,是软件开发中的一个热点。也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高开发的效率。
8.2AOP的作用及其优势
- 作用:在程序运行期间,在不修改源码的情况下对方法进行功能增强
- 优势:减少重复代码,提高开发效率,并且便于维护
8.3AOP的底层实现
实际上,AOP的底层实现是通过Spring提供的动态代理技术实现的。在运行期间,Spring通过动态代理技术动态生成代理对象,代理对象方法执行时进行增强功能的介入,在去调试目标对象的方法,从而完成功能的增强。
8.4AOP的动态代理技术
常用的动态代理技术
- JDK代理:基于接口的动态代理技术
- cglib代理:基于父类的动态代理技术
8.5JDK的动态代理
public interface TargetInterface {
public void save();
}
public class Target implements TargetInterface {
public void save() {
System.out.println("save running...");
}
}
public class Advice {
public void before(){
System.out.println("前置增强");
}
public void after(){
System.out.println("后置增强");
}
}
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.before(); //后置增强
return invoke;
}
}
);
//调用代理对象的方法
proxy.save();
}
}
输出结果
前置增强
save running...
前置增强
8.6cglib的动态代理
public class Target{
public void save() {
System.out.println("save running...");
}
}
public class Advice {
public void before(){
System.out.println("前置增强");
}
public void after(){
System.out.println("后置增强");
}
}
public class ProxyTest {
public static void main(final 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 o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
advice.before();
Object invoke = method.invoke(target, args);
advice.after();
return invoke;
}
});
//4.创建代理对象
Target proxy = (Target)enhancer.create();
proxy.save();
}
}
输出结果
前置增强
save running...
前置增强
8.7AOP的相关概念
Spring的AOP实现底层就是对上面的动态代理进行了封装,封装后我们只需要对需要关注的部分进行代码编写,并通过配置的方式完成指定目标的方法增强。
在正式讲解AOP的操作之前,我们必须理解AOP的相关术语,常用的术语如下:
- Target(目标对象):代理的目标对象
- Proxy(代理):一个类被AOP植入增强后,就产生一个代理类
- Joinpoint(连接点):所谓连接点是指那些被拦截的点。在Spring中,这些点指的是方法,因为Spring只支持方法类型的连接点
- Pointcut(切入点):所谓切入点是指我们要对哪些Joinpoint进行拦截的定义
- Advice(通知/增强):所谓通知是指拦截到Joinpoint之后所要做的事情就是通知
- Aspect(切面):是切入点和通知(引介)的结合
- Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程。Spring采用动态代理织入,而Aspect采用编译期织入和类装载期织入
8.8AOP开发明确的事项
-
需要编写的内容
- 编写核心业务代码(目标类的目标方法)
- 编写切面类,切面类中有通知(增强功能的方法)
- 在配置文件中,配置织入关系,即将哪些通知与哪些连接点进行结合
-
AOP技术实现的内容
Spring框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。
-
AOP底层使用哪种代理方式
在Spring中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式。
8.9知识要点
- AOP:面向切面编程
- AOP底层实现:基于JDk的动态代理和基于Cglib的动态代理
- AOP的重点概念:
- Pointcut(切入点):被增强的方法
- Advice(通知/增强):封装增强业务的方法
- Aspect(切面):切点+通知
- Weaving(织入):将切点和通知结合的过程
- 开发明确事项:
- 谁是切点(切点表达式配置)
- 谁是通知(切面类中的增强方法)
- 将切点和通知进行织入
九、基于XML的AOP开发
9.1快速入门
- 导入AOP相关的坐标
- 创建目标接口和目标类(内部有切点)
- 创建切面类(内部有增强方法)
- 将目标类和切面类的对象创建权交给Spring
- 在applicationContext.xml中配置织入关系
- 测试代码
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
public interface TargetInterface {
public void save();
}
public class Target implements TargetInterface {
public void save() {
System.out.println("save running...");
}
}
public class MyAspect {
public void before(){
System.out.println("前置增强");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans 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.d105.aop.Target"></bean>
<!--配置切面对象-->
<bean id="myAspect" class="com.d105.aop.MyAspect"></bean>
<!--配置织入:告诉Spring框架那些方法(切点)需要进行那些增强(前置,后置)-->
<aop:config>
<!--声明切面-->
<aop:aspect ref="myAspect">
<!--切面:切点+通知-->
<aop:before method="before" pointcut="execution(public void com.d105.aop.Target.save())"/>
</aop:aspect>
</aop:config>
</beans>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test {
@Autowired
@Qualifier("target")
private TargetInterface target;
@org.junit.Test
public void test(){
target.save();
}
}
输出结果
前置增强
save running...
9.2XML配置AOP详解
-
切点表达式的写法
表达式语法
execution([修饰符] 返回值类型 包名.类名.方法名.(参数))
- 访问修饰符可以省略
- 返回值类型、包名、类名、方法名可以使用星号*代表任意
- 包名与类名之间一个点.代表当前包下的类,两个点…表示当前包及其包下的类
- 参数列表可以使用两个点…表示任意类型的参数列表
例如:
execution(public void com.d105.aop.Target.save()) execution(void com.d105.aop.Target.*(..)) execution(* com.d105.aop.*.*(..)) execution(* com.d105.aop..*.*(..)) execution(* *..*.*(..))
-
通知的类型
通知的配置语法
<aop:通知类型 method="切面类中方法名" pointcut="切面表达式"/>
名称 标签 说明 前置通知 aop:before 用于配置前置通知。指定增强的方法在切入点方法之前执行 后置通知 aop:after-returning 用于配置后置通知。指定增强的方法在切入点方法之后执行 环绕通知 aop:around 用于配置环绕通知。指定增强的方法在切入点方法之前和之后都执行 异常抛出通知 aop:after-throwing 用于配置异常抛出通知。指定增强的方法在出现异常时执行 最终通知 aop:after 用于配置最终通知。无论增强方式执行是否有异常都会执行 after-returning:
<aop:after-returning method="afterReturning" pointcut="execution(* com.d105.aop.*.*(..))"/>
public void afterReturning(){ System.out.println("后置增强"); }
around:
//ProceedingJoinPoint :正在执行的连接点==切点 public Object around(ProceedingJoinPoint pjp)throws Throwable{ System.out.println("环绕前增强.."); Object proceed = pjp.proceed();//切点方法 System.out.println("环绕后增强.."); return proceed; }
<aop:around method="around" pointcut="execution(* com.d105.aop.*.*(..))"/>
after-throwing:
public void afterThrowing(){ System.out.println("异常抛出增强"); }
public void save() { int i=1/0; System.out.println("save running..."); }
<aop:after-throwing method="afterThrowing" pointcut="execution(* com.d105.aop.*.*(..))"/>
after:
public void after(){ System.out.println("最终增强"); }
<aop:after method="after" pointcut="execution(* com.d105.aop.*.*(..))"/>
-
切点表达式的抽取
当多个增强的切点表达式相同时,可以将表达式进行抽取,在增强中使用pointcut-ref属性代替pointcut属性来引用抽取后的切点表达式。
<aop:config> <!--声明切面--> <aop:aspect ref="myAspect"> <!--抽取切点表达式--> <aop:pointcut id="myPointcut" expression="execution(* com.d105.aop.*.*(..))"/> <aop:after method="after" pointcut-ref="myPointcut"/> </aop:aspect> </aop:config>
9.3知识要点
-
AOP织入的配置
<aop:config> <!--声明切面--> <aop:aspect ref="myAspect"> <!--抽取切点表达式--> <aop:pointcut id="myPointcut" expression="execution(* com.d105.aop.*.*(..))"/> <!--切面:切点+通知--> <aop:before method="before" pointcut="execution(public void com.d105.aop.Target.save())"/> <aop:after-returning method="afterReturning" pointcut="execution(* com.d105.aop.*.*(..))"/> <aop:around method="around" pointcut="execution(* com.d105.aop.*.*(..))"/> <aop:after-throwing method="afterThrowing" pointcut="execution(* com.d105.aop.*.*(..))"/> <aop:after method="after" pointcut-ref="myPointcut"/> </aop:aspect> </aop:config>
-
通知的类型:前置通知、后置通知、环绕通知、异常抛出通知、最终通知
-
切点表达式的写法:
execution([修饰符] 返回值类型 包名.类名.方法名.(参数))
十、基于注解开发的AOP开发
10.1快速入门
基于注解的AOP开发步骤:
- 创建目标接口和目标类(内部有切点)
- 创建切面类(内部有增强方法)
- 将目标类和切面类的对象创建权交给Spring
- 在切面类中使用注解配置织入关系
- 在配置文件中开启组件扫描和AOP的自动代理
- 测试
public interface TargetInterface {
public void save();
}
@Component("target")
public class Target implements TargetInterface {
public void save() {
System.out.println("save running...");
}
}
@Component("myAspect")
@Aspect //标注当前当前myAspect是一个切面类
public class MyAspect {
//配置前置增强
@Before(value = "execution(* com.d105.anno.*.*(..))")
public void before(){
System.out.println("前置增强");
}
//配置后置增强
@AfterReturning(value = "execution(* com.d105.anno.*.*(..))")
public void afterReturning(){
System.out.println("后置增强");
}
//ProceedingJoinPoint :正在执行的连接点==切点
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("最终增强");
}
}
<!-- 开启组件扫描-->
<context:component-scan base-package="com.d105"/>
<!-- AOP的自动代理-->
<aop:aspectj-autoproxy/>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AnnoTest {
@Autowired
@Qualifier("target")
private TargetInterface target;
@org.junit.Test
public void test(){
target.save();
}
}
输出结果
前置增强
save running...
后置增强
10.2注解配置AOP详解
-
注解通知的类型
通知的配置语法:@通知注解(“切点表达式”)
名称 标签 说明 前置通知 @Before 用于配置前置通知。指定增强的方法在切入点方法之前执行 后置通知 @AfterReturning 用于配置后置通知。指定增强的方法在切入点方法之后执行 环绕通知 @Around 用于配置环绕通知。指定增强的方法在切入点方法之前和之后都执行 异常抛出通知 @AfterThrowing 用于配置异常抛出通知。指定增强的方法在出现异常时执行 最终通知 @After 用于配置最终通知。无论增强方式执行是否有异常都会执行 -
切点表达式的抽取
同xml配置AOP一样,我可以将切点表达式抽取。抽取方式是在切面内定义方法,在该方法上使用@Pointcut注解定义切点表达式,然后在在增强注解中进行引用。具体如下:
@Component("myAspect") @Aspect //标注当前当前myAspect是一个切面类 public class MyAspect { //配置前置增强 // @Before(value = "execution(* com.d105.anno.*.*(..))") @Before("pointcut()") public void before(){ System.out.println("前置增强"); } //配置后置增强 //@AfterReturning(value = "execution(* com.d105.anno.*.*(..))") @AfterReturning("MyAspect.pointcut()") public void afterReturning(){ System.out.println("后置增强"); } //ProceedingJoinPoint :正在执行的连接点==切点 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("最终增强"); } //定义切点表达式 @Pointcut("execution(* com.d105.anno.*.*(..))") public void pointcut(){} }
10.3知识要点
-
注解AOP开发步骤
- 使用@Aspect标注切面类
- 使用@通知注解通知方法
- 在配置文件中配置AOP自动代理aop:aspectj-autoproxy/
-
通知注解类型
名称 标签 说明 前置通知 @Before 用于配置前置通知。指定增强的方法在切入点方法之前执行 后置通知 @AfterReturning 用于配置后置通知。指定增强的方法在切入点方法之后执行 环绕通知 @Around 用于配置环绕通知。指定增强的方法在切入点方法之前和之后都执行 异常抛出通知 @AfterThrowing 用于配置异常抛出通知。指定增强的方法在出现异常时执行 最终通知 @After 用于配置最终通知。无论增强方式执行是否有异常都会执行
十一、Spring JDBC Template基本使用
11.1JBDCTemplate概述
它是Spring框架中提供的一个对象,是对原始繁琐的JDBCTemplate和HibernateTemplate,操作nosql数据库的RedisTemplate,操作消息的JMSTemplate等等。
11.2JDBCTemplate开发步骤
- 导入spring-jdbc和spring-tx坐标
- 创建数据库表和实体
- 创建JDBCTemplate对象
- 执行数据库操作
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
`name` varchar(255) DEFAULT NULL,
`money` double DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
public class Account {
private String name;
private double money;
public Account() {
}
public Account(String name, double money) {
this.name = name;
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"name='" + name + '\'' +
", money=" + money +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
}
public class JdbcTemplateTest {
@Test
//测试JDBCTemplate开发步骤
public void test1()throws Exception{
//创建数据源对象
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/d105?serverTimezone=UTC");
dataSource.setUser("root");
dataSource.setPassword("123456");
JdbcTemplate jdbcTemplate = new JdbcTemplate();
//设置数据源对象,知道数据库在哪
jdbcTemplate.setDataSource(dataSource);
//执行操作
int row = jdbcTemplate.update("insert into account values(?,?)", "汤姆", 5000);
System.out.println(row);
}
输出结果
1
11.4Spring产生JDBCTemplate对象
我们可以将JDBCTemplate的创建权交给Spring,将数据源DataSource的创建权也交给Spring,在Spring容器内部将数据源DataSource注入到JDBCTemplate魔板对象中能够,配置如下:
<!-- 数据源DataSource-->
<bean id="dataSources" 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>
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
@Test
public void test2(){
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate)applicationContext.getBean("jdbcTemplate");
int row = jdbcTemplate.update("insert into account values(?,?)", "杰瑞", 5000);
System.out.println(row);
}
输出结果
1
11.5JDBCTemplate的常用操作
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JDBCTemplateCRUDTest {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void testUpdate(){
int row = jdbcTemplate.update("update account set money=? where name =?", 10000, "汤姆");
System.out.println(row);
}
@Test
public void testDelete(){
jdbcTemplate.update("delete from account where name =?","杰瑞");
}
@Test
public void testQueryAll(){
List<Account> accounts = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
System.out.println(accounts);
}
@Test
public void testQueryOne(){
Account account = jdbcTemplate.queryForObject("select * from account where name =?", new BeanPropertyRowMapper<Account>(Account.class), "汤姆");
System.out.println(account);
}
@Test
public void testQueryCount(){
Long aLong = jdbcTemplate.queryForObject("select count(*) from account", Long.class);
System.out.println(aLong);
}
}
11.6知识要点
-
导入spring-jdbc和spring-tx坐标
-
创建数据库表和实体
-
创建JDBCTemplate对象
JdbcTemplate jdbcTemplate = new JdbcTemplate(); //设置数据源对象,知道数据库在哪 jdbcTemplate.setDataSource(dataSource);
-
执行数据库操作
更新操作:
jdbcTemplate.update(sql,params)
查询操作:
jdbcTemplate.query(sql,Mapper,params)
jdbcTemplate.queryObject(sql,Mapper,params)
十二、编程式事务控制相关对象
12.1PlatformTransactionManager
PlatformTransactionManager接口是Spring的事务管理器,它里面提供了我们常用的操作事务的方法。
方法 | 说明 |
---|---|
TransactionStatus getTransaction(TransactionDefination defination) | 获取事务的状态信息 |
void conmit(TransactionStatus status) | 提交事务 |
void rollback(TransactionStatus status) | 回滚事务 |
注意:
PlatformTransactionManager是接口类型,不同的Dao层技术则有不同的实现类,例如:Dao层技术是JDBC或Mybatis时:org,springframework.jdbc.datasource.DataSourceTransactionManager
Dao层技术是hibernate:org.springframework.ormhibernate5.HibernateTransactionManager
12.2TransactionDefination
TransactionDefination 是事务的定义信息对象,里面有如下方法:
方法 | 说明 |
---|---|
int getIsolationLevel() | 获取事务的隔离级别 |
int getPropogationBehavior() | 获得事务的传播行为 |
int getTimeout() | 获得超时时间 |
boolean isReadInly() | 是否只读 |
-
事务隔离级别
设置隔离级别,可以解决事务并发产生的问题,如脏读、不可重复读和虚读。
- ISOLATION_DEFAULT
- ISOLATION_READ_UNCOMMITTED
- ISOLATION_READ_COMMITTED
- ISOLATION_REPEATABLE_READ
- ISOLATION_SERIALLZABLE
-
事务传播行为
12.3TransactionStatus
TransactionStatus接口提供的是事务具体的运行状态,方法介绍如下。
方法 | 说明 |
---|---|
boolean hasSavepoint() | 是否存储回滚点 |
boolean isCompleted() | 事务是否完成 |
boolean isNewTransaction() | 是否是新事务 |
boolean isRollbackonly() | 事务是否回报 |
12.4知识要点
-
PlatformTransactionManager
-
TransactionDefination
-
TransactionStatus
十三、基于XML的声明式事务控制
13.1什么是声明式事务控制
Spring的声明式事务顾名思义就是采用声明的方式来处理事务。这里所说的声明,就是指配置文件中声明,用Spring配置文件中声明的处理事务代替代码式的处理事务。
声明式事务处理的作用
-
事务管理不侵入开发的组件。具体来说,业务逻辑对象就不会意识到正在事务管理之中,事实上也应该如此,因为事务管理是属于系统层面的服务,而不是业务逻辑的一部分,如果想要改变事务管理策划的话,也只需要在定义文件中重新配置即可
-
在不需要事务管理的时候,只要在设定文件上修改一下,即可移去事务管理服务,无需改变代码重新编译,这样维护起来及其方便
注意:Spring声明式事务控制底层就是AOP
13.2声明式事务控制的实现
声明式事务控制明确事项:
- 谁是切点?
- 谁是通知
- 配置切面
13.3切点方法的事务参数的配置
<!--通知 事务的增强-->
<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="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
其中,<tx:method >代表切点方法的参数的配置,列
<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
- name:切点方法名称
- isolation:事务的隔离级别
- propogation:事务的传播行为
- timeout:超时时间
- read-only:是否只读
13.4知识要点
声明式事务控制的配置要点
- 平台事务管理器配置
- 事务通知的配置
- 事务AOP织入的配置
13.5注解配置声明式事务控制解析
- 使用@Transactional在需要进行事务控制的类或方法上修饰,注解可用的属性同xml配置方式,例如隔离级别、传播行为、超时时间、是否只读
- 注解使用在类上,那么该类下的所有方法都使用同一套注解参数配置
- 使用在方法上,不同的方法可以采用不同的事务参数配置
- Xml配置文件中要开启事务的注解驱动<tx:annotation-driven />
13.6知识要点
注解声明式事务控制的配置要点
- 平台事务管理器配置(xml方式)
- 事务通知的配置(@Transactional注解配置)
TransactionStatus接口提供的是事务具体的运行状态,方法介绍如下。
方法 | 说明 |
---|---|
boolean hasSavepoint() | 是否存储回滚点 |
boolean isCompleted() | 事务是否完成 |
boolean isNewTransaction() | 是否是新事务 |
boolean isRollbackonly() | 事务是否回报 |
12.4知识要点
-
PlatformTransactionManager
-
TransactionDefination
-
TransactionStatus
十三、基于XML的声明式事务控制
13.1什么是声明式事务控制
Spring的声明式事务顾名思义就是采用声明的方式来处理事务。这里所说的声明,就是指配置文件中声明,用Spring配置文件中声明的处理事务代替代码式的处理事务。
声明式事务处理的作用
-
事务管理不侵入开发的组件。具体来说,业务逻辑对象就不会意识到正在事务管理之中,事实上也应该如此,因为事务管理是属于系统层面的服务,而不是业务逻辑的一部分,如果想要改变事务管理策划的话,也只需要在定义文件中重新配置即可
-
在不需要事务管理的时候,只要在设定文件上修改一下,即可移去事务管理服务,无需改变代码重新编译,这样维护起来及其方便
注意:Spring声明式事务控制底层就是AOP
13.2声明式事务控制的实现
声明式事务控制明确事项:
- 谁是切点?
- 谁是通知
- 配置切面
13.3切点方法的事务参数的配置
<!--通知 事务的增强-->
<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="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
其中,<tx:method >代表切点方法的参数的配置,列
<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
- name:切点方法名称
- isolation:事务的隔离级别
- propogation:事务的传播行为
- timeout:超时时间
- read-only:是否只读
13.4知识要点
声明式事务控制的配置要点
- 平台事务管理器配置
- 事务通知的配置
- 事务AOP织入的配置
13.5注解配置声明式事务控制解析
- 使用@Transactional在需要进行事务控制的类或方法上修饰,注解可用的属性同xml配置方式,例如隔离级别、传播行为、超时时间、是否只读
- 注解使用在类上,那么该类下的所有方法都使用同一套注解参数配置
- 使用在方法上,不同的方法可以采用不同的事务参数配置
- Xml配置文件中要开启事务的注解驱动<tx:annotation-driven />
13.6知识要点
注解声明式事务控制的配置要点
- 平台事务管理器配置(xml方式)
- 事务通知的配置(@Transactional注解配置)
- 事务注解驱动的配置<tx:annotation-driven />