SSM—Spring(动态代理及AOP&JdbcTemplate&事务控制)


1.AOP

  • AOP(Aspect Oriented Programming)—面向切面编程,是通过预编译方式和运行期动态代理实现程序功能的统—维护的—种技术,可以在程序运行期间不修改源码的情况下进行功能增强。AOP是OOP 的延续,利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,减少了重复代码,提高程序的可重用性,同时提高了开发的效率。
  • 实际上,AOP的底层是通过Spring提供的的动态代理技术实现的。在运行期间,Spring通过动态代理技术动态的生成代理对象,代理对象方法执行时进行增强功能的介入,在去调用目标对象的方法,从而完成功能的增强

AOP相关术语

  • Target(目标对象)︰代理的目标对象
  • Proxy(代理):一个类被AOP织入增强后,就产生一个结果代理类
  • Joinpoint(连接点)∶指那些被拦截到的点。在spring中,这些点指的是可以被增强的方法,因为spring只支持方法类型的连接点
  • Pointcut(切入点)︰指要对哪些Joinpoint进行拦截的定义(真正被增强的方法)
  • Advice(通知/增强)︰指拦截到Joinpoint之后所要做的事情
  • Aspect(切面)︰是切入点通知(引介)的结合
  • Weaving (织入)︰是指把增强应用到目标对象来创建新的代理对象的过程。spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入

Spring框架监控切入点(Pointcut)方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象,根据通知(Advice)类别,在代理对象的对应位置,将通知对应的功能织入(Weaving),完成完整的代码逻辑运行。

1.1动态代理

  • 动态代理技术
    • JDK代理:基于接口
    • cglib代理:基于父类
    • AOP的底层实现是对这两种技术进行封装,在spring中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式.
      在这里插入图片描述

JDK动态代理的思路:
在这里插入图片描述
生成代理对象的测试代码

public class ProxyTest {
    public static void main(String[] args) {
        //创建目标对象
        final Target target = new Target();
        //获得增强对象
        final Enhance enhance = new Enhance();

        //创建代理对象,Proxy.newProxyInstance(目标对象的类加载器,目标对象实现的接口的字节码对象数组,InvocationHandler接口)
        //返回的就是动态生成的代理对象(接口,因为jdk动态代理是基于接口实现的)
        TargetInterface proxy = (TargetInterface) Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new InvocationHandler() {
                    //调用代理对象的任何方法,实质执行的是invoke()方法
                    //Method method代表 代理对象当前执行的方法的描述对象(反射)
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        enhance.before();//前置增强
                        Object invoke = method.invoke(target, args);//根据指定对象调用由此 Method 对象表示的底层方法
                        enhance.after();//后置增强
                        return invoke;
                    }
                });
        //调用代理对象的方法(即TargetInterface接口里的方法,但实质执行的是上面的invoke()方法)
        proxy.save();
    }
}

在这里插入图片描述

1.2 基于xml的AOP

1.AOP的jar包在spring-context包中,但aspectj框架中对于AOP的实现更优秀,下面的代码也是基于aspectj进行配置

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.6</version>
</dependency>

2.创建目标接口和目标类(内部有切点Pointcut)
在这里插入图片描述
3.创建切面(Aspect)类(内部有增强(Advice)方法)

//切面类
public class Aspect {
    //增强方法
    public void save(){
        System.out.println("save running");
    }
}

4.将目标类和切面类的对象创建权交给spring,并在applicationContext.xml中配置织入关系(注意要引入aop的命名空间)

<?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-3.0.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--    配置目标类-->
    <bean id="target" class="com.kk.aop_xml.Target"/>
<!--    配置切面类-->
    <bean id="aspect" class="com.kk.aop_xml.Aspect"/>
<!--配置织入关系,告诉spring容器哪些切点(方法)需要哪些增强(advice:前置、后置...增强)-->
    <aop:config>
<!--    引用Aspect类作为切面-->
        <aop:aspect ref="aspect">
<!--        切面=切点+增强。配置Target的save方法(切点)执行时要进行Aspect的before方法前置增强-->
            <aop:before method="before" pointcut="execution(public void com.kk.aop_xml.Target.save())"/>
        </aop:aspect>
    </aop:config>
</beans>

6.测试代码
整合JUnit

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test1 {
    @Autowired
    private TargetInterface target;
    @Test
    public void test(){
        target.save();
    }
}

在这里插入图片描述
AOP配置文件详解

  • 切点(Pointcut)表达式语法:execution([修饰符] 返回值类型 包名.类名.方法名(参数))
    • 修饰符可以省略
    • 返回值类型、包名、类名、方法名可以使用星号*代表任意
    • 包名与类名之间一个点.代表当前包下的类,两个点 … 表示当前包及其子包下的类
    • 参数列表可以使用两个点 … 表示任意个数,任意类型的参数列表
  • 通知(Advice)配置语法 :< aop:通知类型 method="切面类中方法名" pointcut="切点表达式"></ aop:通知类型>
    • < aop:before>:配置前置通知。指定增强的方法在切入点方法之前执行
    • < aop:after-returning>:配置后置通知。指定增强的方法在切入点方法之后执行
    • < aop:around>:配置环绕通知。指定增强的方法在切入点方法之前和之后都执行
    • < aop:throwing>:配置异常抛出通知。指定增强的方法在出现异常时执行
    • < aop:after>:配置最终通知。无论增强方式执行是否有异常都会执行
  • 切点表达式的抽取
<!--    引用Aspect类作为切面-->
       <aop:aspect ref="aspect">
<!--        抽取切点表达式-->
           <aop:pointcut id="pointcut" expression="execution(* com.kk.aop_xml.*.*(..))"/>
<!--        切面=切点+增强。配置Target的save方法(切点)执行时要进行Aspect的before方法前置增强-->
<!--            <aop:before method="before" pointcut="execution(public void com.kk.aop_xml.Target.save())"/>-->
           <aop:before method="before" pointcut-ref="pointcut"/>
       </aop:aspect>

1.3 基于注解的AOP

  • @Aspect:标注该类为切面类
  • @Poitncut:定义切点表达式
  • 通知的注解类型:@Before、@AfterReturning、@Around、@AfterThrowing、@After

1.创建接口和目标类以及切面类

@Component("target")
public class Target implements TargetInterface {

    public void save() {
        System.out.println("save running");
    }
}
@Component("aspect")
@Aspect
public class MyAspect {
    //增强方法
    @Before("execution(* com.kk.aop_xml.*.*(..))")
    public void before(){
        System.out.println("前置增强");
    }

	//抽取切点表达式
    @Before("MyAspect.myPointcut()")
    public void save(){
        System.out.println("前置增强");
    }
    @Pointcut("execution(* com.kk.aop_anno.*.*(..))")
    public void myPointcut(){}
}

2.在配置文件中开启组件扫描和AOP自动代理

<!--    基于注解的配置-->
<context:component-scan base-package="com.kk.aop_anno"/>
<aop:aspectj-autoproxy/>

与上面的测试结果一致

2.JDBCTemplate

JDBCTemplate(JDBC模板)是spring框架中提供的一个对象,是对原始繁琐的Jdbc API对象的简单封装。spring框架为我们提供了很多的操作模板类。例如:操作关系型数据的JdbcTemplate和HibernateTemplate,操作nosal数据库的RedisTemplate,操作消息队列的JmsTemplate等等。下面根据一个例子来展示如何使用该模板类:

1.导入spring和spring-tx坐标

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.5</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.3.5</version>
</dependency>

2.创建数据库表和实体
在这里插入图片描述
Account实体类,get,set方法省略

public class Account {
    private int id;
    private String username;
    private String money;
}   

3.测试

public class TestJdbc {
    @Test
    public void test1() throws PropertyVetoException {
        //创建数据源对象
        ComboPooledDataSource cp = new ComboPooledDataSource();
        cp.setDriverClass("com.mysql.cj.jdbc.Driver");
        cp.setJdbcUrl("jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=ture&characterEncoding=UTF-8&serverTimezone=UTC");
        cp.setUser("root");
        cp.setPassword("root");
        //创建JDBCTemplate对象
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        //设置数据源对象,获得connection对象
        jdbcTemplate.setDataSource(cp);
        //执行crud操作
        jdbcTemplate.update("insert into account values(?,?,?)",4,"kk",5000);
    }
}

可以看到测试操作时十分繁琐,可以使用配置文件让Spring容器来创建数据源和JdbcTemplate对象。

<!--    加载外部properties文件-->
<context:property-placeholder location="classpath:db.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>
<!--    JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
</bean>

接下来再看测试代码

    @Test
    public void test1() throws PropertyVetoException {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jdbcTemplate = (JdbcTemplate) ac.getBean("jdbcTemplate");
        jdbcTemplate.update("insert into account values(?,?,?)",5,"kk1",3000);
    }

在这里插入图片描述
CRUD其他操作的测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestCrud {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Test
    public void testUpdate(){
        //增删改均调用update方法
        //jdbcTemplate.update("update account set name=? where id=?","ljk",1);
        jdbcTemplate.update("delete from account where name=?","kk1");
    }
    @Test
    public void testQueryAll(){
        //new BeanPropertyRowMapper<T>(T.class),表示要将查询到的结果封装到该类中
        List<Account> accountList = jdbcTemplate.query("select * from account",
                new BeanPropertyRowMapper<Account>(Account.class));
        for (Account account : accountList) {
            System.out.println(account);
        }
    }
    @Test
    public void testQuery(){
        Account account = jdbcTemplate.queryForObject("select * from account where id=?",
                new BeanPropertyRowMapper<Account>(Account.class), 1);
        System.out.println(account);
    }
    @Test
    public void testQueryCount(){
        //计算有几个用户
        Long aLong = jdbcTemplate.queryForObject("select count(*) from account", Long.class);
        System.out.println(aLong);
    }
}

注意进行单个查询时应选择如下的方法
在这里插入图片描述

3.事务控制

3.1 编程式事务控制的相关对象

编程式:调用Java的API进行相关操作(Spring底层实现方式);声明式:通过配置文件实现操作,以代替代码式的操作

  • PlatformTransactionManager接口,是spring的事务管理器,提供了常用的操作事务的方法,如下:
    • Transactionstatus getTransaction (TransactionDefination defination):获取事务的状态信息
    • void commit (Transactionstatus status):提交事务
    • void rollback (Transactionstatus status):回滚事务
  • TransactionDefinition,是定义事务信息的对象,有如下方法:
    • int getIsolationLevel ():获得事务的隔离级别
      • 设置隔离级别,可以解决事务并发产生的问题,如脏读、不可重复读和虚读。
      • ISOLATION_DEFAULT
      • ISOLATION_READ_UNCOMMITTED
      • ISOLATION_READ_COMMITTED
      • ISOLATION_REPEATABLE_READ
      • ISOLATION_SERIALIZABLE
    • int getPropogationBehavior ():获得事务的传播行为
      • REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
      • SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
      • MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
      • REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
      • NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起NEVER:以非事务方式运行,如果当前存在事务,抛出异常
      • NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行REQUIRED类似的操作
      • 超时时间:默认值是-1,没有超时限制。如果有,以秒为单位进行设置
      • 是否只读:建议查询时设置为只读
    • int getTimeout ():获得超时时间
    • boolean isReadonly ():是否只读
  • TransactionStatus接口,提供事务具体的运行状态,方法如下:
    • boolean hassavepoint ():是否存储回滚点
    • boolean iscompleted ( ):事务是否完成
    • boolean isNewTransaction ():是否是新事务
    • boolean isRollbackonly ():事务是否回滚

3.2 基于xml的声明式事务控制

声明式事务处理的作用: (Spring声明式事务控制底层就是AOP)

  • 事务管理不侵入开发的组件。具体来说,业务逻辑对象就不会意识到正在事务管理之中,事实上也应该如此,因为事务管理是属于系统层面的服务,而不是业务逻辑的一部分,如果想要改变事务管理策划的话,也只需要在定义文件中重新配置即可
  • 在不需要事务管理的时候,只要在设定文件上修改一下,即可移去事务管理服务,无需改变代码重新编译,这样维护起来极其方便

测试环境搭建
在这里插入图片描述
按照数据库表创建实体类,并创建业务层、持久层
在这里插入图片描述
配置事务控制(需要引入sop和tx)

<?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"
       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-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx.xsd">

<!--    加载外部properties文件-->
    <context:property-placeholder location="classpath:db.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>
<!--    JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="accountDao" class="com.kk.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
<!--目标对象,内部方法就是切点-->
    <bean id="accountService" class="com.kk.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>
<!--配置平台事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--通知,事务的增强-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--        设置事务的属性信息TransactionDefinition-->
        <tx:attributes>
<!--            设置哪些方法被增强 isolation隔离级别;propagation事务传播行为;timeout超时时间;read-only是否只读-->
            <tx:method name="transform" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="1" read-only="false"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
<!--配置事务的AOP织入-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.kk.service.impl.*.*(..))"/>
    </aop:config>
</beans>

控制层

public class AccountController {
    public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = (AccountService) app.getBean("accountService");
        accountService.transform("A","B",200);
    }
}

3.3 基于注解的声明式事务控制

找到切点,进行事务控制(增强)

@Service("accountService")
//@Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)//对该类的全部方法进行事务控制
public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;
    @Autowired
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)//就近原则
    public void transform(String outMan,String inMan,double money){
        accountDao.out(outMan,money);
        int i = 1/0;
        accountDao.in(inMan,money);
    }
}

使用注解后的配置文件

<!--    组件扫描-->
    <context:component-scan base-package="com.kk"/>

<!--    加载外部properties文件-->
    <context:property-placeholder location="classpath:db.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>
<!--    JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

<!--配置平台事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

<!--    注解,需要配置事务的注解驱动-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值