Home > Java > javaTutorial > body text

How to configure Java Spring's annotation-based AOP

PHPz
Release: 2023-05-17 17:37:06
forward
1058 people have browsed it

    1 Environment setup

    1.1 Step 1: Prepare necessary code and jar package

    • Copy A short project is enough.

    1.2 Step 2: Import the context namespace in the configuration file

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:context="http://www.springframework.org/schema/context"
        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
            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">
     
        <!-- 配置数据库操作对象 -->
        <bean id="dbAssit" class="com.itheima.dbassit.DBAssit">
            <property name="dataSource" ref="dataSource"></property>
            
            <!-- 指定 connection 和线程绑定 -->
            <property name="useCurrentConnection" value="true"></property>
        </bean>
     
        <!-- 配置数据源 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql:///spring_day02"></property>
            <property name="user" value="root"></property>
            <property name="password" value="1234"></property>
        </bean>
    </beans>
    Copy after login

    1.3 Step 3: Configure resource usage annotations

    • Account’s business layer implementation class

    @Service("accountService")
    public class AccountServiceImpl implements IAccountService {
     
        @Autowired
        private IAccountDao accountDao;
    }
    Copy after login
    • Account’s persistence layer implementation class

    @Repository("accountDao")
    public class AccountDaoImpl implements IAccountDao {
        @Autowired
        private DBAssit dbAssit ;
    }
    Copy after login

    1.4 Step 4: Specify the packages to be scanned by spring in the configuration file

    <!-- 告知 spring,在创建容器时要扫描的包 -->
    <context:component-scan base-package="com.itheima"></context:component-scan>
    Copy after login

    2 Configuration steps

    2.1 Step 1: Configure the notification class using annotations

    • Transaction Control Class

    @Component("txManager")
    public class TransactionManager {
     
        //定义一个 DBAssit
        @Autowired
        private DBAssit dbAssit ;
    }
    Copy after login

    2.2 Step 2: Use the @Aspect annotation on the notification class to declare it as an aspect

    • Function:

      • Declare the current class as an aspect class.

    • Transaction control class

    @Component("txManager")
    @Aspect//表明当前类是一个切面类
    public class TransactionManager {
     
        //定义一个 DBAssit
        @Autowired
        private DBAssit dbAssit ;
    }
    Copy after login

    2.3 Step 3: Use annotations to configure notifications on the enhanced method

    2.3.1 @Before
    • Function:

      • Treat the current method as a pre-notification.

    • Attributes:

      • value: used to specify the entry point expression, you can also specify the entry point expression Quote.

    //开启事务
    @Before("execution(* com.itheima.service.impl.*.*(..))")
    public void beginTransaction() {
     
        try {
            dbAssit.getCurrentConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    Copy after login
    2.3.2 @AfterReturning
    • Function:

      • Think of the current method as a post-advice.

    • Attributes:

      • value: used to specify the entry point expression, you can also specify the entry point expression Quote

    //提交事务
    @AfterReturning("execution(* com.itheima.service.impl.*.*(..))")
    public void commit() {
     
        try {
            dbAssit.getCurrentConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    Copy after login
    2.3.3 @AfterThrowing
    • Function:

      • Consider the current method as an exception notification.

    • Attributes:

      • value: used to specify the entry point expression, you can also specify the entry point expression Quote

    //回滚事务
    @AfterThrowing("execution(* com.itheima.service.impl.*.*(..))")
    public void rollback() {
     
        try {
            dbAssit.getCurrentConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    Copy after login
    2.3.4 @After
    • Function:

      • Consider the current method as the final notification.

    • Attributes:

      • value: used to specify the entry point expression, you can also specify the entry point expression Quote

    //释放资源
    @After("execution(* com.itheima.service.impl.*.*(..))")
    public void release() {
     
        try {
            dbAssit.releaseConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    Copy after login

    2.4 Step 4: Enable spring’s support for annotation AOP in the spring configuration file

    <!-- 开启 spring 对注解 AOP 的支持 -->
    <aop:aspectj-autoproxy/>
    Copy after login

    3 Surround notification annotation configuration @Around

    • Function:

      • Treat the current method as a surrounding notification.

    • Attributes:

      • value: used to specify the entry point expression, you can also specify the entry point expression Quote.

    /**
    * 环绕通知
    * @param pjp
    * @return
    */
    @Around("execution(* com.itheima.service.impl.*.*(..))")
    public Object transactionAround(ProceedingJoinPoint pjp) {
     
        //定义返回值
        Object rtValue = null;
     
        try {
        
            //获取方法执行所需的参数
            Object[] args = pjp.getArgs();
        
            //前置通知:开启事务
            beginTransaction();
     
            //执行方法
            rtValue = pjp.proceed(args);
     
            //后置通知:提交事务
            commit();
            }catch(Throwable e) {
     
            //异常通知:回滚事务
            rollback();
            e.printStackTrace();
        }finally {
     
        //最终通知:释放资源
        release();
        }
     
        return rtValue;
    }
    Copy after login

    4 Pointcut expression annotation @Pointcut

    • Function:

      • Specify the entry point expression

    • Attributes:

      • value: The content of the specified expression

    @Pointcut("execution(* com.itheima.service.impl.*.*(..))")
    private void pt1() {}
     
        /**
        * 引用方式:
        * 环绕通知
        * @param pjp
        * @return
        */
        @Around("pt1()")//注意:千万别忘了写括号
        public Object transactionAround(ProceedingJoinPoint pjp) {
     
        //定义返回值
        Object rtValue = null;
     
        try {
            //获取方法执行所需的参数
            Object[] args = pjp.getArgs();
     
            //前置通知:开启事务
            beginTransaction();
            
            //执行方法
            rtValue = pjp.proceed(args);
     
            //后置通知:提交事务
            commit();
        }catch(Throwable e) {
     
            //异常通知:回滚事务
            rollback();
            e.printStackTrace();
        }finally {
     
            //最终通知:释放资源
            release();
        }
        
        return rtValue;
    }
    Copy after login

    5 Configuration method without XML

    @Configuration
    @ComponentScan(basePackages="com.itheima")
    @EnableAspectJAutoProxy
    public class SpringConfiguration {
     
    }
    Copy after login

    The above is the detailed content of How to configure Java Spring's annotation-based AOP. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template