search
HomeJavajavaTutorialHow to configure Java Spring's annotation-based AOP

How to configure Java Spring's annotation-based AOP

May 17, 2023 pm 05:37 PM
javaspringaop

    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>

    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;
    }
    • Account’s persistence layer implementation class

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

    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>

    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 ;
    }

    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 ;
    }

    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();
        }
    }
    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();
        }
    }
    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();
        }
    }
    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();
        }
    }

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

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

    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;
    }

    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;
    }

    5 Configuration method without XML

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

    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!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

    Start Spring using IntelliJIDEAUltimate version...

    How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

    When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

    How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

    How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

    How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

    Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

    How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

    Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

    E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

    Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

    How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

    How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools