Spring之XML 配置AOP 事务管理

简介: Spring之XML 配置AOP 事务管理


XML中配置AOP


       切面类 正常写通知 不用加注解

public class MyAspect {
    //前置通知
    public void mybefore(){
        System.out.println("前置通知");
    }
    //后置通知
    public void myaftereturning(Object obj){
        System.out.println("后置通知");
    }
    //环绕通知
    public void myAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕通知11");
        Object proceed = proceedingJoinPoint.proceed();
        System.out.println("环绕通知11");
    }
    //最终通知
    public void myafter(){
        System.out.println("最终通知");
    }
    //异常通知
    public void myafterThrowing(Throwable e){
        System.out.println("异常通知");
        System.out.println(e.getMessage());
    }
}

     

目标类


public class UserServiceImpl implements UserService {
    public void eat(){
        int i = 1 / 0;
        System.out.println("吃饭");
    }
}

xml:  

   


       步骤:        


               1.配置UserServiceImpl 将UserServcieImpl放入                    Spring容器

               2.配置切面类

               3.配置切面 切入点 通知


<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
                  http://www.springframework.org/schema/mvc/spring-mvc.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
                  http://www.springframework.org/schema/tx
                  http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--配置userService 将UserServiceImpl放入SpringIoc容器-->
    <bean id = "userService" class = "com.czxy.demo04.service.impl.UserServiceImpl"></bean>
    <!--配置切面类-->
    <bean id = "myAspect" class="com.czxy.demo04.aspect.MyAspect"></bean>
    <!--配置切面-->
    <aop:config>
        <aop:aspect ref = "myAspect">
            <!--切入点-->
            <aop:pointcut id = "myPointcut" expression = "execution(* com.czxy.demo04.service.impl.UserServiceImpl.*(..))"></aop:pointcut>
            <aop:before method = "mybefore" pointcut-ref = "myPointcut"></aop:before>
            <aop:after-returning method="myaftereturning" pointcut-ref="myPointcut" returning="obj"></aop:after-returning>
            <aop:around method="myAround" pointcut-ref="myPointcut"></aop:around>
            <aop:after method="myafter" pointcut-ref="myPointcut"></aop:after>
            <aop:after-throwing method="myafterThrowing" pointcut-ref="myPointcut" throwing="e"></aop:after-throwing>
        </aop:aspect>
    </aop:config>
</beans>

  测试类


@RunWith(SpringRunner.class)
@ContextConfiguration(locations = {"classpath:demo04.xml"})
public class TestA {
    @Resource(name = "userService")
    private UserService userService;
    @Test
    public void test01(){
        userService.eat();
    }
}

XML中配置事务管理


       转账 当出现错误的时候 转账失败 并且余额不变


       xml配置类步骤:


               1.加载属性配置文件


               2.配置连接池


               3.配置sessionFactory


               4.扫描dao的包


               5.配置service


               6.定义事务管理器


               7.配置事务属性


               8.配置事务切入点


domain:


@Entity(name = "account")
public class Account {
    @Id
    private Integer id;
    private String name;
    private Float money;

 

mapper:


public interface AccountMapper extends Mapper<Account> {
}

 

转账类:


public class AccountServiceImpl implements AccountService {
    private AccountMapper accountMapper;
    public void setAccountMapper(AccountMapper accountMapper) {
        this.accountMapper = accountMapper;
    }
    public void change(Integer outId, Integer inId, Float money) {
        Account outAccount = accountMapper.selectByPrimaryKey(outId);
        outAccount.setMoney(outAccount.getMoney() - money);
        accountMapper.updateByPrimaryKey(outAccount);
         int i = 1 / 0;
        Account inAccount = accountMapper.selectByPrimaryKey(inId);
        inAccount.setMoney(inAccount.getMoney() + money);
        accountMapper.updateByPrimaryKey(inAccount);
    }
}


 测试类:


@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath:demo05.xml")
public class TestA {
    @Resource(name = "accountService")
    private AccountService accountService;
    @Test
    public void testDemo(){
        accountService.change(1,2,3f);
        System.out.println("转账成功");
    }
}

 

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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
                  http://www.springframework.org/schema/mvc/spring-mvc.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
                  http://www.springframework.org/schema/tx
                  http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 1.1 指定配置文件的位置-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 1.2 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!-- 配置初始化大小、最小、最大连连接数量 -->
        <property name="initialSize" value="5"/>
        <property name="minIdle" value="10"/>
        <property name="maxActive" value="20"/>
    </bean>
    <!-- 2.1 sessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.czxy.demo05.domain" />
        <property name="configuration">
            <bean class="org.apache.ibatis.session.Configuration">
                <property name="mapUnderscoreToCamelCase" value="true" />
            </bean>
        </property>
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageHelper">
                    <property name="properties">
                        <props>
                            <prop key="dialect">mysql</prop>
                            <prop key="rowBoundsWithCount">true</prop>
                        </props>
                    </property>
                </bean>
            </array>
        </property>
    </bean>
    <!-- 2.2 扫描Dao的包 -->
    <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定会话工厂 -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 指定 mybatis 接口所在的包 -->
        <property name="basePackage" value="com.czxy.demo05.mapper"/>
    </bean>
    <!-- 3 配置service -->
    <bean id="accountService" class="com.czxy.demo05.service.impl.AccountServiceImpl">
        <property name="accountMapper" ref="accountMapper" />
    </bean>
    <!-- 4 配置事务 -->
    <!-- 4.1 定义事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 4.2 配置事务属性 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager" >
        <tx:attributes>
            <tx:method name="change" propagation="REQUIRED"/>
            <tx:method name="*" read-only="true" />
        </tx:attributes>
    </tx:advice>
    <!-- 4.3 配置事务切入点 -->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.czxy.demo05.service..*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut" />
    </aop:config>
</beans>
相关文章
|
负载均衡 监控 Java
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
本文详细介绍了 Spring Cloud Gateway 的核心功能与实践配置。首先讲解了网关模块的创建流程,包括依赖引入(gateway、nacos 服务发现、负载均衡)、端口与服务发现配置,以及路由规则的设置(需注意路径前缀重复与优先级 order)。接着深入解析路由断言,涵盖 After、Before、Path 等 12 种内置断言的参数、作用及配置示例,并说明了自定义断言的实现方法。随后重点阐述过滤器机制,区分路由过滤器(如 AddRequestHeader、RewritePath、RequestRateLimiter 等)与全局过滤器的作用范围与配置方式,提
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
|
Java 关系型数据库 MySQL
Spring Boot自动配置:魔法背后的秘密
Spring Boot 自动配置揭秘:只需简单配置即可启动项目,背后依赖“约定大于配置”与条件化装配。核心在于 `@EnableAutoConfiguration` 注解与 `@Conditional` 系列条件判断,通过 `spring.factories` 或 `AutoConfiguration.imports` 加载配置类,实现按需自动装配 Bean。
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
3254 0
|
XML 安全 Java
使用 Spring 的 @Aspect 和 @Pointcut 注解简化面向方面的编程 (AOP)
面向方面编程(AOP)通过分离横切关注点,如日志、安全和事务,提升代码模块化与可维护性。Spring 提供了对 AOP 的强大支持,核心注解 `@Aspect` 和 `@Pointcut` 使得定义切面与切入点变得简洁直观。`@Aspect` 标记切面类,集中处理通用逻辑;`@Pointcut` 则通过表达式定义通知的应用位置,提高代码可读性与复用性。二者结合,使开发者能清晰划分业务逻辑与辅助功能,简化维护并提升系统灵活性。Spring AOP 借助代理机制实现运行时织入,与 Spring 容器无缝集成,支持依赖注入与声明式配置,是构建清晰、高内聚应用的理想选择。
1078 0
|
XML Java 数据格式
《深入理解Spring》:AOP面向切面编程深度解析
Spring AOP通过代理模式实现面向切面编程,将日志、事务等横切关注点与业务逻辑分离。支持注解、XML和编程式配置,提供五种通知类型及丰富切点表达式,助力构建高内聚、低耦合的可维护系统。
|
前端开发 Java 应用服务中间件
《深入理解Spring》 Spring Boot——约定优于配置的革命者
Spring Boot基于“约定优于配置”理念,通过自动配置、起步依赖、嵌入式容器和Actuator四大特性,简化Spring应用的开发与部署,提升效率,降低门槛,成为现代Java开发的事实标准。
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
2227 5
|
传感器 Java 数据库
探索Spring Boot的@Conditional注解的上下文配置
Spring Boot 的 `@Conditional` 注解可根据不同条件动态控制 Bean 的加载,提升应用的灵活性与可配置性。本文深入解析其用法与优势,并结合实例展示如何通过自定义条件类实现环境适配的智能配置。
886 0
探索Spring Boot的@Conditional注解的上下文配置
|
人工智能 监控 安全
Spring AOP切面编程颠覆传统!3大核心注解+5种通知类型,让业务代码纯净如初
本文介绍了AOP(面向切面编程)的基本概念、优势及其在Spring Boot中的使用。AOP作为OOP的补充,通过将横切关注点(如日志、安全、事务等)与业务逻辑分离,实现代码解耦,提升模块化程度、可维护性和灵活性。文章详细讲解了Spring AOP的核心概念,包括切面、切点、通知等,并提供了在Spring Boot中实现AOP的具体步骤和代码示例。此外,还列举了AOP在日志记录、性能监控、事务管理和安全控制等场景中的实际应用。通过本文,开发者可以快速掌握AOP编程思想及其实践技巧。
|
设计模式 Java 开发者
如何快速上手【Spring AOP】?从动态代理到源码剖析(下篇)
Spring AOP的实现本质上依赖于代理模式这一经典设计模式。代理模式通过引入代理对象作为目标对象的中间层,实现了对目标对象访问的控制与增强,其核心价值在于解耦核心业务逻辑与横切关注点。在框架设计中,这种模式广泛用于实现功能扩展(如远程调用、延迟加载)、行为拦截(如权限校验、异常处理)等场景,为系统提供了更高的灵活性和可维护性。
1698 0