一. IOC 和 DI

IOC : 控制反转,将对象的创建权反转给了 Spring。
DI  : 依赖注入,前提是必须要有 IOC 的环境,Spring 管理这个类的时候将类的依赖的属性注入(设置)进来。

二. 工厂类

  1. // 1. 加载类路径
  2. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  3. UserDao userDao = (UserDao) applicationContext.getBean("userDao");
  4. userDao.save();
  5.  
  6. // 2. 加载磁盘中的 文件路径
  7. ApplicationContext applicationContext = new FileSystemXmlApplicationContext("C:/Users/Administrator/Desktop/applicationContext.xml");
  8. UserDao userDao = (UserDao) applicationContext.getBean("userDao");
  9. userDao.save();

三. Bean 的作用范围配置 (xml 文件中)

1. scope : Bean 的作用范围。
!    - singleton     : 默认,Spring 会采用单例模式创建这个对象。
!    - prototype     : 多例模式。(Struts2 和 Spring 整合时会用到)
    - request       : 应用在 Web 项目中,Spring 创建这个类以后,将这个类存入到 request 范围中。
    - session       : 应用在 Web 项目中,Spring 创建这个类以后,将这个类存入到 session 范围中。
    - globalsession : 应用在 Web 项目中,必须在 porlet 环境下使用,如果没有这个环境,相对于 session。

四. Spring 的属性注入方式(xml)

1. 构造方法
// 构造方法 (需要提供构造器)

  1. <!-- 1. 构造方法 -->
  2. <bean id="shop" class="com.q.spring.demo2.ShopDao">
  3. <constructor-arg name="name" value="apple" />
  4. <constructor-arg name="price" value="100" />
  5. </bean>
  1. @Test
  2. public void demo1(){
  3. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  4. ShopDao shopDao = (ShopDao) applicationContext.getBean("shop");
  5. System.out.println(shopDao);
  6.  
  7. }

2. set 方式的属性注入

  1. <!-- 2. set 方法 -->
  2. <bean id="shop2" class="com.q.spring.demo2.ShopDao2">
  3. <property name="name" value="pear" />
  4. <property name="price" value="22" />
  5. </bean>
  6.  
  7. <!-- 2. set 方法 (p名称空间属性注入) -->
  8. <bean id="shop2" class="com.q.spring.demo2.ShopDao2" p:name="q" p:price="2222"></bean>
  9.  
  10. <!-- 2. set 方法 (SpEL 属性注入) -->
  11. <bean id="shop2" class="com.q.spring.demo2.ShopDao2">
  12. <property name="name" value="#{'q1'}"></property>
  13. <property name="price" value="#{111}"></property>
  14. </bean>
  1. // set 方式的属性注入(需要提供 set 方法)
  2. @Test
  3. public void demo2(){
  4. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  5. ShopDao2 shopDao = (ShopDao2) applicationContext.getBean("shop2");
  6. System.out.println(shopDao);
  7.  
  8. }

3. set 方法注入对象类型 (属性中依赖类)

  1. <!-- 3. set 方法注入对象类型的属性 -->
  2. <bean id="person" class="com.q.spring.demo2.Person">
  3. <property name="name" value="q" />
  4. <property name="shopDao2" ref="shop2" />
  5. </bean>
  6.  
  7. <!-- 3. set 方法注入对象类型的属性 (p名称空间属性注入) -->
  8. <bean id="person" class="com.q.spring.demo2.Person" p:name="q1" p:shopDao2-ref="shop2"></bean>
  9.  
  10. <!-- 3. set 方法注入对象类型的属性 (SpEL 属性注入) -->
  11. <bean id="person" class="com.q.spring.demo2.Person">
  12. <property name="name" value="#{'q1'}"></property>
  13. <property name="shopDao2" value="#{shop2}"></property>
  14. </bean>
  1. // set 方法注入对象类型(需要提供 set 方法)
  2. @Test
  3. public void demo3(){
  4. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  5. Person person = (Person) applicationContext.getBean("person");
  6. System.out.println(person);
  7.  
  8. }

4. p名称空间属性注入

  1. <bean id="person" class="com.q.spring.demo2.Person" p:name="q1" p:shopDao2-ref="shop2"></bean>

5. SpEL 属性注入 (Spring 3.0 之后)

  1. <bean id="shop2" class="com.q.spring.demo2.ShopDao2">
  2. <property name="name" value="#{'q1'}"></property>
  3. <property name="price" value="#{111}"></property>
  4. </bean>

6. 集合类型的注入 ( arrs list set map )

  1. private String[] arrs;
  2. private List<String> list;
  3. private Set<String> set;
  4. private Map<String, String> map;
  1. <bean id="typealls" class="com.q.spring.demo2.typeAlls">
  2. <!-- 数组类型 -->
  3. <property name="arrs">
  4. <list>
  5. <value>a</value>
  6. <value>b</value>
  7. <value>c</value>
  8. </list>
  9. </property>
  10.  
  11. <!-- list集合 -->
  12. <property name="list">
  13. <list>
  14. <value>a1</value>
  15. <value>b1</value>
  16. <value>c1</value>
  17. </list>
  18. </property>
  19.  
  20. <!-- set集合 -->
  21. <property name="set">
  22. <set>
  23. <value>a1</value>
  24. <value>b1</value>
  25. <value>c1</value>
  26. </set>
  27. </property>
  28.  
  29. <!-- map 集合 -->
  30. <property name="map">
  31. <map>
  32. <entry key="b2" value="b2" />
  33. <entry key="b2" value="b2" />
  34. <entry key="b2" value="b2" />
  35. </map>
  36. </property>
  37.  
  38. </bean>

五. 分模块开发的配置

1. 直接在一个xml文件中导入

  1. <import resource="applicationContext.xml" />

2. 在创建 ClassPathXmlApplicationContext 时可传多个参数路径

  1. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml1""applicationContext.xml2");

六. Spring 的 IOC 注解开发

1. 引入约束: 使用注解开发引入 Context 约束

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
  4. http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd
  6. http://www.springframework.org/schema/context
  7. http://www.springframework.org/schema/context/spring-context.xsd">
  8. </beans>

2. 开启 Spring 的组件扫描

  1. <!-- 配置组件扫描(哪些包下的类使用IOC注解) -->
  2. <context:component-scan base-package="包路径"></context:component-scan>

3. 在类上添加注解

- @Component : 组件
    - 装饰一个类,将这个类交给 Spring 管理。

- 这个注解有三个衍生注解:        - @Controller : web 层
        - @Service       : service 层
        - @Repository : dao 层

  1. import org.springframework.stereotype.Component;
  2.  
  3. // value 可省略: @Component("shopDao")
  4. @Component(value = "userDao") // 相当于在 <bean id="userDao" class="com.q.spring.demo2.userDemo2" />
  5. public class userDemo2 implements UserDao {
  6. public void save(){
  7.  
  8. }
  9. }

4. 注解方式设置属性值

注解方式:使用注解方式,可以没有 set 方法。

- 属性如果有 set 方法,需要将属性注入的注解加到 set 方法上。

  1. // 如:
  2. @Value("添加注解")
  3. public void setName(String name){
  4. this.name = name;
  5. }

- 属性如果没有 set 方法,需要将属性注入的注解添加到属性上。

  1. // 如:
  2. @Value("添加注解")
  3. private String name;

5. 属性注入的注解

# 普通属性:
    @Value     : 设置普通属性的值
# 对象类型属性:
    @Autowired : 设置对象类型的属性值。但是按照类型完成属性注入(按照类名的一致)。
        - 可以通过 @Qualifier 和 @Autowired 配合使用来修改为按照名称属性注入。
        
    @Resource  : 完成对象类型的属性注入,按照名称完成属性注入。 (常用)。

6. Bean 的其他注解

# 生命周期相关注解:
    @PostConstruct   : 初始化方法
    @PreDestroy         : 销毁方法

# Bean 作用范围的注解:
    @scope    : 作用范围
    参数:
        - singleton : 默认单例
        - prototype : 多例

七. Spring 的 AOP 的 XML 开发
 
1. applocationContext.xml 文件配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xsi:schemaLocation="
  6. http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/aop
  9. http://www.springframework.org/schema/aop/spring-aop.xsd">
  10.  
  11. <!-- 配置目标对象 :被增强的对象 -->
  12. <bean id="productDao" class="com.q.spring.demo1.ProductDaoImpl" />
  13.  
  14. <!-- 将切面类交给 Spring 管理 -->
  15. <bean id="myAspect" class="com.q.spring.demo1.MyAspectXml" />
  16.  
  17. <aop:config>
  18. <!-- 通过AOP的配置完成对目标类产生代理 -->
  19. <aop:pointcut expression="execution(* com.q.spring.demo1.ProductDaoImpl.save(..))" id="pointcut1" />
  20. <aop:pointcut expression="execution(* com.q.spring.demo1.ProductDaoImpl.delete(..))" id="pointcut2" />
  21. <aop:pointcut expression="execution(* com.q.spring.demo1.ProductDaoImpl.update(..))" id="pointcut3" />
  22. <aop:pointcut expression="execution(* com.q.spring.demo1.ProductDaoImpl.find(..))" id="pointcut4" />
  23.  
  24. <!-- 配置切面 -->
  25. <aop:aspect ref="myAspect">
  26. <!-- 前置通知:获得切入点信息 -->
  27. <aop:before method="checkPri" pointcut-ref="pointcut1" />
  28.  
  29. <!-- 后置通知 -->
  30. <aop:after-returning method="writeLog" pointcut-ref="pointcut2" returning="result" />
  31.  
  32. <!-- 环绕通知 -->
  33. <aop:around method="around" pointcut-ref="pointcut3" />
  34.  
  35. <!-- 异常抛出通知 -->
  36. <aop:after-throwing method="afterThrowing" pointcut-ref="pointcut4" throwing="ex" />
  37.  
  38. <!-- 最终通知 -->
  39. <aop:after method="after" pointcut-ref="pointcut4" />
  40. </aop:aspect>
  41. </aop:config>
  42. </beans>

2. ProductDao.java  接口文件

  1. package com.q.spring.demo1;
  2.  
  3. public interface ProductDao {
  4. public void save();
  5. public void update();
  6. public String delete();
  7. public void find();
  8. }

3. ProductDaoImpl.java  DAO文件

  1. package com.q.spring.demo1;
  2.  
  3. public class ProductDaoImpl implements ProductDao {
  4.  
  5. @Override
  6. public void save() {
  7. System.out.println("save");
  8. }
  9.  
  10. @Override
  11. public void update() {
  12. System.out.println("update");
  13. }
  14.  
  15. @Override
  16. public String delete() {
  17. System.out.println("delete");
  18. return "Delete!!!";
  19. }
  20.  
  21. @Override
  22. public void find() {
  23. System.out.println("find");
  24. // int i = 1/0;
  25. }
  26. }

4. MyAspectXML.java

  1. package com.q.spring.demo1;
  2.  
  3. // 切面类
  4.  
  5. import org.aspectj.lang.JoinPoint;
  6. import org.aspectj.lang.ProceedingJoinPoint;
  7.  
  8. public class MyAspectXml {
  9.  
  10. // 前置通知
  11. public void checkPri(JoinPoint joinpoint){
  12. System.out.println("权限校验 "+ joinpoint);
  13. }
  14.  
  15. // 后置通知
  16. public void writeLog(Object result){
  17. System.out.println("日志记录 "+ result);
  18. }
  19.  
  20. // 环绕通知 : 性能监控
  21. public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
  22. System.out.println("环绕前通知...");
  23. Object obj = joinPoint.proceed();
  24. System.out.println("环绕后通知...");
  25. return obj;
  26. }
  27.  
  28. // 异常抛出通知
  29. public void afterThrowing(Throwable ex){
  30. System.out.println("异常抛出通知..."+ ex.getMessage());
  31. }
  32.  
  33. // 最终通知:类似于 finally
  34. public void after(){
  35. System.out.println("最终通知...");
  36. }
  37. }

5. 测试文件

  1. package com.q.spring.demo1;
  2.  
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.test.context.ContextConfiguration;
  6. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  7.  
  8. import javax.annotation.Resource;
  9.  
  10. @RunWith(SpringJUnit4ClassRunner.class)
  11. @ContextConfiguration("classpath:applicationContext.xml")
  12. public class SpringDemo1 {
  13.  
  14. @Resource(name="productDao")
  15. private ProductDao productDao;
  16.  
  17. @Test
  18. public void demo1(){
  19. productDao.save();
  20. productDao.update();
  21. productDao.delete();
  22. productDao.find();
  23. }
  24. }

八. Srping 的 AOP 注解

1. applocationContext.xml 文件

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xsi:schemaLocation="
  6. http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context.xsd
  10. http://www.springframework.org/schema/aop
  11. http://www.springframework.org/schema/aop/spring-aop.xsd">
  12.  
  13. <!-- 在配置文件中开启注解的AOP开发 -->
  14. <aop:aspectj-autoproxy />
  15.  
  16. <!-- 配置目标类 -->
  17. <bean id="orderDao" class="com.q.spring.demo1.OrderDao" />
  18.  
  19. <!-- 配置切面类 -->
  20. <bean id="myAspect" class="com.q.spring.demo1.MyAspectAnno" />
  21. </beans>

2. OrderDao.java 文件

  1. package com.q.spring.demo1;
  2.  
  3. public class OrderDao {
  4. public void save(){
  5. System.out.println("save...");
  6. }
  7.  
  8. public void update(){
  9. System.out.println("update...");
  10. }
  11.  
  12. public String delete(){
  13. System.out.println("delete...");
  14. return "Delete!!!";
  15. }
  16.  
  17. public void find(){
  18. System.out.println("find...");
  19. // int i = 1/0;
  20. }
  21. }

3. MyAspectAnno.java 文件

  1. package com.q.spring.demo1;
  2.  
  3. import org.aspectj.lang.ProceedingJoinPoint;
  4. import org.aspectj.lang.annotation.*;
  5.  
  6. @Aspect
  7. public class MyAspectAnno {
  8.  
  9. // 前置通知
  10. // execution(* com.q.spring.demo1.OrderDao.save(..))
  11. @Before(value = "MyAspectAnno.pointcut1()")
  12. public void befor(){
  13. System.out.println("前置增强");
  14. }
  15.  
  16. // 后置通知
  17. @AfterReturning(value = "MyAspectAnno.pointcut3()", returning = "result")
  18. public void afterReturning(Object result){
  19. System.out.println("后置增强 "+ result);
  20. }
  21.  
  22. // 环绕通知
  23. @Around(value = "MyAspectAnno.pointcut2()")
  24. public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
  25. System.out.println("环绕前增强");
  26. Object obj = joinPoint.proceed();
  27. System.out.println("环绕后增强");
  28. return obj;
  29. }
  30.  
  31. // 异常抛出通知
  32. @AfterThrowing(value = "MyAspectAnno.pointcut4()", throwing = "e")
  33. public void afterThrowing(Throwable e){
  34. System.out.println("异常抛出增强: "+e);
  35. }
  36.  
  37. // 最终通知
  38. @After(value = "MyAspectAnno.pointcut4()")
  39. public void afterThrowing(){
  40. System.out.println("最终增强");
  41. }
  42.  
  43. // 切入点注解
  44. @Pointcut(value = "execution(* com.q.spring.demo1.OrderDao.save(..))")
  45. private void pointcut1(){}
  46. @Pointcut(value = "execution(* com.q.spring.demo1.OrderDao.update(..))")
  47. private void pointcut2(){}
  48. @Pointcut(value = "execution(* com.q.spring.demo1.OrderDao.delete(..))")
  49. private void pointcut3(){}
  50. @Pointcut(value = "execution(* com.q.spring.demo1.OrderDao.find(..))")
  51. private void pointcut4(){}
  52. }

4. SpringDemo1.java 文件

  1. package com.q.spring.demo1;
  2.  
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.test.context.ContextConfiguration;
  6. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  7.  
  8. import javax.annotation.Resource;
  9.  
  10. @RunWith(SpringJUnit4ClassRunner.class)
  11. @ContextConfiguration("classpath:applicationContext.xml")
  12. public class SpringDemo1 {
  13.  
  14. @Resource(name = "orderDao")
  15. private OrderDao orderDao;
  16.  
  17. @Test
  18. public void demo1(){
  19. orderDao.save();
  20. orderDao.update();
  21. orderDao.delete();
  22. orderDao.find();
  23. }
  24.  
  25. }

九. Spring 的 JDBC 模板
Spring 是一站式框架,有持久层解决方案

1. DBCP 连接池
# 文档..

2. C3P0 连接池

  1. # applicationContext.xml 配置
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:aop="http://www.springframework.org/schema/aop"
  7. xsi:schemaLocation="
  8. http://www.springframework.org/schema/beans
  9. http://www.springframework.org/schema/beans/spring-beans.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context.xsd
  12. http://www.springframework.org/schema/aop
  13. http://www.springframework.org/schema/aop/spring-aop.xsd">
  14.  
  15. <!-- 配置C3P0连接池 -->
  16. <!-- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">-->
  17. <!-- <property name="driverClass" value="com.mysql.jdbc.Driver" />-->
  18. <!-- <property name="jdbcUrl" value="jdbc:mysql:///spring_jdbc" />-->
  19. <!-- <property name="user" value="root" />-->
  20. <!-- <property name="password" value="chaoqi" />-->
  21. <!-- </bean>-->
  22.  
  23. <!-- 引入属性文件 -->
  24. <context:property-placeholder location="classpath:jdbc.properties" />
  25.  
  26. <!-- 配置C3P0连接池 -->
  27. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  28. <property name="driverClass" value="${jdbc.driverClass}" />
  29. <property name="jdbcUrl" value="${jdbc.url}" />
  30. <property name="user" value="${jdbc.username}" />
  31. <property name="password" value="${jdbc.password}" />
  32. </bean>
  33.  
  34. <!-- 配置 Spring JDBC的模板 -->
  35. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  36. <property name="dataSource" ref="dataSource" />
  37. </bean>
  38. </beans>

# 增删改查操作

  1. package com.q.jdbc.demo1;
  2.  
  3. import com.q.jdbc.domain.Account;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.jdbc.core.JdbcTemplate;
  7. import org.springframework.jdbc.core.RowMapper;
  8. import org.springframework.test.context.ContextConfiguration;
  9. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  10.  
  11. import javax.annotation.Resource;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.util.List;
  15.  
  16. @RunWith(SpringJUnit4ClassRunner.class)
  17. @ContextConfiguration("classpath:applicationContext.xml")
  18. public class JdbcDemo2 {
  19.  
  20. @Resource(name = "jdbcTemplate")
  21. private JdbcTemplate jdbcTemplate;
  22.  
  23. // 增
  24. @Test
  25. public void demo1(){
  26. jdbcTemplate.update("insert into account values(null,?,?)","q4",152d);
  27. }
  28.  
  29. // 改
  30. @Test
  31. public void demo2(){
  32. jdbcTemplate.update("update account set name=?, money = ? where id=? ","q1test",11d,2 );
  33. }
  34.  
  35. // 删
  36. @Test
  37. public void demo3(){
  38. jdbcTemplate.update("delete from account where id=? ",2);
  39. }
  40.  
  41. // 查
  42. @Test
  43. public void demo4(){
  44. String name = jdbcTemplate.queryForObject("select name from account where id=?",String.class,3);
  45. System.out.println(name);
  46. }
  47.  
  48. // 统计查询
  49. @Test
  50. public void demo5(){
  51. Long count = jdbcTemplate.queryForObject("select count(*) from account",Long.class);
  52. System.out.println(count);
  53. }
  54.  
  55. // 封装到一个对象中
  56. @Test
  57. public void demo6(){
  58. Account account = jdbcTemplate.queryForObject("select * from account where id = ?", new MyRowMapper(), 3);
  59. System.out.println(account);
  60. }
  61.  
  62. // 查询多条记录
  63. @Test
  64. public void demo7(){
  65. List<Account> list = jdbcTemplate.query("select * from account", new MyRowMapper());
  66. for(Account account : list){
  67. System.out.println(account);
  68. }
  69. }
  70.  
  71. class MyRowMapper implements RowMapper<Account>{
  72.  
  73. @Override
  74. public Account mapRow(ResultSet res, int rowNum) throws SQLException {
  75.  
  76. Account account = new Account();
  77. account.setId(res.getInt("id"));
  78. account.setName(res.getString("name"));
  79. account.setMoney(res.getDouble("money"));
  80.  
  81. return account;
  82. }
  83. }
  84. }

十. Spring 的事务传播行为

1. 报则保证多个操作在同一个事务中

PROPAGATION_REQUIRED  : 默认值,如果A中有事务,使用A中的事务,如果A没有,创建一个新的事务,将操作包含进来。
PROPAGATION_SUPPORTS  : 支持事务
,如果A中有事务,使用A中的事务,如果没有,则不使用事务。
PROPAGATION_MANDATORY : 如果A中有事务,使用A中的事务,如果A中没有事务,则抛异常。

2. 保证多个操作不在同一个事务中

PROPAGATION_REQUIRES_NEW  : 如果A中有事务,将A的事务挂起(暂停), 创建新事务,只包含自身操作。
                            如果A中没有事务,则创建一个新事务,包含自身操作
PROPAGATION_NOT_SUPPORTED : 如果A中有事务,将A的事务挂起,不使用事务管理。
PROPAGATION_NEVER           : 如果A中有事务,则抛异常。

3. 嵌套式事务

PROPAGATION_NESTED    : 嵌套事务,如果A中有事务,按照A的事务执行,执行完毕后,设置一个保存点,执行B中的操作,如果没有异常,执行通过,如果有异常,可以选择回滚到最初始的位置,也可以回滚到保存点。

十一. Spring 声明式事务管理一 (XML)
XML 步骤:
1. 引入 aop 开发包。
2. 配置事务管理器。
3. 配置增强<tx:Advice>
4. 配置aop

# 1. XML 文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop.xsd
  13. http://www.springframework.org/schema/cache
  14. http://www.springframework.org/schema/cache/spring-cache.xsd
  15. http://www.springframework.org/schema/tx
  16. http://www.springframework.org/schema/tx/spring-tx.xsd">
  17.  
  18. <!-- 配置 Service -->
  19. <bean id="accountService" class="com.q.tx.demo2.AccountServiceImpl">
  20. <property name="accountDao" ref="accountDao" />
  21. </bean>
  22.  
  23. <!-- 配置 DAO -->
  24. <bean id="accountDao" class="com.q.tx.demo2.AccountDaoImpl">
  25. <property name="dataSource" ref="dataSource" />
  26. </bean>
  27.  
  28. <!-- 配置连接池的JDBC模板 -->
  29. <!-- 引入属性文件 -->
  30. <context:property-placeholder location="classpath:jdbc.properties" />
  31.  
  32. <!-- 配置C3P0连接池 -->
  33. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  34. <property name="driverClass" value="${jdbc.driverClass}" />
  35. <property name="jdbcUrl" value="${jdbc.url}" />
  36. <property name="user" value="${jdbc.username}" />
  37. <property name="password" value="${jdbc.password}" />
  38. </bean>
  39.  
  40. <!-- 配置事务管理 -->
  41. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  42. <property name="dataSource" ref="dataSource" />
  43. </bean>
  44.  
  45. <!-- 配置事务的增强 -->
  46. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  47. <tx:attributes>
  48. <tx:method name="*" propagation="REQUIRED" />
  49.  
  50. <!-- 实际开发中: -->
  51. <!-- <tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" />-->
  52. <!-- <tx:method name="update*" propagation="REQUIRED" />-->
  53. <!-- <tx:method name="delete*" propagation="REQUIRED" />-->
  54. <!-- <tx:method name="find*" read-only="true" />-->
  55. </tx:attributes>
  56. </tx:advice>
  57.  
  58. <!-- AOP的配置 -->
  59. <aop:config>
  60. <aop:pointcut id="pointcut1" expression="execution(* com.q.tx.demo2.AccountServiceImpl.*(..))"/>
  61. <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut1" />
  62. </aop:config>
  63. </beans>
  1. # jdbc.propertie.xml 文件属性设置
  2. jdbc.driverClass=com.mysql.jdbc.Driver
  3. jdbc.url=jdbc:mysql:///spring_jdbc
  4. jdbc.username=root
  5. jdbc.password=chaoqi

# 2.  AccountDaoImpl.java 文件

  1. package com.q.tx.demo2;
  2.  
  3. import org.springframework.jdbc.core.support.JdbcDaoSupport;
  4.  
  5. // 转账Dao实现
  6. public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
  7.  
  8. @Override
  9. public void outMoney(Integer from, Double money) {
  10. this.getJdbcTemplate().update("update account set money = money - ? where id = ?", money, from);
  11. }
  12.  
  13. @Override
  14. public void inMoney(Integer to, Double money) {
  15. this.getJdbcTemplate().update("update account set money = money + ? where id = ?", money, to);
  16. }
  17. }

# 3. AccountServiceImpl.java 文件

  1. package com.q.tx.demo2;
  2.  
  3. // 转账的业务层实现类
  4. public class AccountServiceImpl implements AccountService {
  5.  
  6. // 注入 DAO
  7. private AccountDao accountDao;
  8.  
  9. public void setAccountDao(AccountDao accountDao) {
  10. this.accountDao = accountDao;
  11. }
  12.  
  13. /*
  14. from : 转出账号
  15. to : 转人账号
  16. money : 转账金额
  17. */
  18.  
  19. @Override
  20. public void transfer(Integer from, Integer to, Double money) {
  21.  
  22. accountDao.outMoney(from, money);
  23. // int i = 1/0;
  24. accountDao.inMoney(to, money);
  25.  
  26. }
  27.  
  28. }

# 4. 测试文件

  1. package com.q.tx.demo2;
  2.  
  3. // 测试类
  4.  
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.springframework.test.context.ContextConfiguration;
  8. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  9.  
  10. import javax.annotation.Resource;
  11.  
  12. @RunWith(SpringJUnit4ClassRunner.class)
  13. @ContextConfiguration("classpath:tx2.xml")
  14. public class SpringDemo1 {
  15.  
  16. @Resource(name = "accountService")
  17. private AccountService accountService;
  18.  
  19. @Test
  20. public void demo1(){
  21. accountService.transfer(1,3,100d);
  22. }
  23.  
  24. }

十二. Spring 声明式事务管理二 (注解方式)
注解 步骤:
1. 引入 aop 开发包。
2. 配置事务管理器。
3. 开启注解事务。
4. 在业务层添加注解

# 1. XML 文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop.xsd
  13. http://www.springframework.org/schema/cache
  14. http://www.springframework.org/schema/cache/spring-cache.xsd
  15. http://www.springframework.org/schema/tx
  16. http://www.springframework.org/schema/tx/spring-tx.xsd">
  17.  
  18. <!-- 配置 Service -->
  19. <bean id="accountService" class="com.q.tx.demo3.AccountServiceImpl">
  20. <property name="accountDao" ref="accountDao" />
  21. </bean>
  22.  
  23. <!-- 配置 DAO -->
  24. <bean id="accountDao" class="com.q.tx.demo3.AccountDaoImpl">
  25. <property name="dataSource" ref="dataSource" />
  26. </bean>
  27.  
  28. <!-- 配置连接池的JDBC模板 -->
  29. <!-- 引入属性文件 -->
  30. <context:property-placeholder location="classpath:jdbc.properties" />
  31.  
  32. <!-- 配置C3P0连接池 -->
  33. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  34. <property name="driverClass" value="${jdbc.driverClass}" />
  35. <property name="jdbcUrl" value="${jdbc.url}" />
  36. <property name="user" value="${jdbc.username}" />
  37. <property name="password" value="${jdbc.password}" />
  38. </bean>
  39.  
  40. <!-- 配置事务管理器 第一步 -->
  41. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  42. <property name="dataSource" ref="dataSource" />
  43. </bean>
  44.  
  45. <!-- 开启注解事务 第二步 -->
  46. <tx:annotation-driven transaction-manager="transactionManager" />
  47. </beans>

# 2. AccountDaoImpl 文件

  1. package com.q.tx.demo3;
  2.  
  3. import org.springframework.jdbc.core.support.JdbcDaoSupport;
  4.  
  5. // 转账Dao实现
  6. public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
  7.  
  8. @Override
  9. public void outMoney(Integer from, Double money) {
  10. this.getJdbcTemplate().update("update account set money = money - ? where id = ?", money, from);
  11. }
  12.  
  13. @Override
  14. public void inMoney(Integer to, Double money) {
  15. this.getJdbcTemplate().update("update account set money = money + ? where id = ?", money, to);
  16. }
  17. }

# 3. AccountServiceImpl 文件

  1. package com.q.tx.demo3;
  2.  
  3. import org.springframework.transaction.annotation.Transactional;
  4.  
  5. // 转账的业务层实现类
  6. // 第三步 需要在要进行事务操作的类上加 @Transactional
  7. @Transactional
  8. public class AccountServiceImpl implements AccountService {
  9.  
  10. // 注入 DAO
  11. private AccountDao accountDao;
  12.  
  13. public void setAccountDao(AccountDao accountDao) {
  14. this.accountDao = accountDao;
  15. }
  16.  
  17. /*
  18. from : 转出账号
  19. to : 转人账号
  20. money : 转账金额
  21. */
  22.  
  23. @Override
  24. public void transfer(Integer from, Integer to, Double money) {
  25.  
  26. accountDao.outMoney(from, money);
  27. // int i = 1/0;
  28. accountDao.inMoney(to, money);
  29.  
  30. }
  31.  
  32. }

# 4. 测试类

  1. package com.q.tx.demo3;
  2.  
  3. // 测试类
  4.  
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.springframework.test.context.ContextConfiguration;
  8. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  9.  
  10. import javax.annotation.Resource;
  11.  
  12. @RunWith(SpringJUnit4ClassRunner.class)
  13. @ContextConfiguration("classpath:tx3.xml")
  14. public class SpringDemo1 {
  15.  
  16. @Resource(name = "accountService")
  17. private AccountService accountService;
  18.  
  19. @Test
  20. public void demo1(){
  21. accountService.transfer(1,3,100d);
  22. }
  23.  
  24. }

Java - 框架之 Spring的更多相关文章

  1. java框架篇---spring AOP 实现原理

    什么是AOP AOP(Aspect-OrientedProgramming,面向方面编程),可以说是OOP(Object-Oriented Programing,面向对象编程)的补充和完善.OOP引入 ...

  2. java框架之Spring(2)-注解配置IOC&AOP配置

    注解配置IoC 准备 1.要使用注解方式配置 IoC,除了之前引入的基础 jar 包,还需要引入 spring-aop 支持包,如下: 2.在 applicationContext.xml 中引入 c ...

  3. java框架篇---spring IOC 实现原理

    IOC(DI):其实这个Spring架构核心的概念没有这么复杂,更不像有些书上描述的那样晦涩.java程序员都知道:java程序中的每个业务逻辑至少需要两个或以上的对象来协作完成,通常,每个对象在使用 ...

  4. Java框架之Spring(四)

    本文主要讲述在Spring中 1 注解方式装配 2 以自动扫描把组件纳入spring容器中管理 3 面象切面编程-代理的jdk 版实现 4 使用 Cglib 生成代理 5 aop编程的一些概念 6 使 ...

  5. java框架之Spring(1)-入门

    介绍 概述 Spring 是一个开放源代码的设计层面框架,它解决的是业务逻辑层和其他各层的松耦合问题,因此它将面向接口的编程思想贯穿整个系统应用.Spring 是于 2003 年兴起的一个轻量级的 J ...

  6. java框架之Spring(4)-Spring整合Hibernate和Struts2

    准备 导包 Struts2 导入 Struts2 zip 包解压目录下 'apps/struts-blank.war' 中所有 jar 包,如下: asm-3.3.jar asm-commons-3. ...

  7. java框架篇---spring hibernate整合

    在会使用hibernate 和spring框架后 两个框架的整合就变的相当容易了, 为什么要整合Hibernate?1.使用Spring的IOC功能管理SessionFactory对象 LocalSe ...

  8. java框架篇---spring aop两种配置方式

    第一种:注解配置AOP 注解配置AOP(使用 AspectJ 类库实现的),大致分为三步: 1. 使用注解@Aspect来定义一个切面,在切面中定义切入点(@Pointcut),通知类型(@Befor ...

  9. java框架篇---spring IOC依赖注入

    spring依赖注入的方式有4种 构造方法注入 属性注入 工厂注入 注解注入 下面通过一个实例统一讲解: User.java package com.bjsxt.model; public class ...

随机推荐

  1. Delphi百度语音【支持语音识别和语音合成】

    作者QQ:(648437169) 点击下载➨百度语音         语音识别api文档         语音合成api文档 [Delphi 百度语音]支持获取 Access Token.语音识别.语 ...

  2. python模块知识四 包和logging日志

    11.包 包:文件夹下具有__init__.py文件就是一个包,包用来管理多个模块 包的结构如下: bake ├── __init__.py ├── api ├── __init__.py ├── p ...

  3. Android--ScrollView边界回弹效果

    /* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Versi ...

  4. AQS(AbstractQueuedSynchronizer)

    AbstractQueuedSynchronizer 是一个锁框架.实现的原理(大概): 1.关于重入锁方面的实现,参考(手写一个可重入锁). 2.关于公平锁方面的实现,使用双链表的形式,进行公平锁的 ...

  5. [BZOJ2739]最远点(DP+分治+决策单调性)

    根据旋转卡壳,当逆时针遍历点时,相应的最远点也逆时针转动,满足决策单调性.于是倍长成链,分治优化DP即可,复杂度O(n^2). #include<cstdio> #include<a ...

  6. 同一个Tomcat部署多个springboot项目问题

    2018-12-13 10:37:21,412 ERROR [localhost-startStop-2] c.a.d.s.DruidDataSourceStatManager [DruidDataS ...

  7. OC与swift相互调用

    一.OC调用swift文件 二.swift调用OC文件 三.注意和总结 添加: 四.自定义桥接文件 一.OC调用swift文件 在OC项目中创建一个swift文件的时候,Xcode 会提示 需要创建一 ...

  8. shell 字符串截取表达式

    ${var#str} 从左向右匹配,非贪婪匹配,截取并保留右边的内容 txt='123456abc123456' echo ${txt#*34} # 56abc123456 ${var##str} 从 ...

  9. RedisCluster的rename机制失败报错,解决又是数据倾斜问题

    需求说明:spring session中的用户session更新是更新key的名字,所以对于key的操作时需要用newkey 替换oldkey value值只允许存在一个,这里用到rename就很合适 ...

  10. go语言 goquery爬虫

      goquery 类似ruby的gem nokogiri goquery的选择器功能很强大,很好用.地址:https://github.com/PuerkitoBio/goquery 这是一个糗百首 ...