Spring AOP——spring基于XML配置的AOP 及 切入点表达式

Spring中基于XML的AOP配置步骤在这里插入代码片
1.把通知bean也交给Spring来管理
2.使用AOP:config标签表明开始AOP的配置
3.使用aop:aspect标签表明配置切面
id属性:是给切面提供一个唯一标识
ref属性:是指定通知类bean的id
4.在aop:aspect标签的内部使用对应标签来配置通知标签
aop:before:表示配置前置通知
method属性:用于指定Logger类中那个方法是前置通知
pointcut属性:用于指定切入点表达式,该表达式的含义指的是对业务层中哪些方法增强
切入点表示的写法
关键字:execution(表达式)
表达式:访问修饰符 返回值 包名.包名.包名…类名.方法名(参数列表)
全通配写法: * *..*.*(..)
实际开发过程中切入点表达式的通常写法:
切入业务层实现类下的所有方法

* com.fy.service.impl.*.*(..)
package com.fy.service;

public interface AccountService {
    /**
     * 模拟保存账户
     */
    void saveAccount();
    /**
     * 模拟更新账户
     */
    void updateAccount(int i);
    /**
     * 模拟删除账户
     */
    int deleteAccount();
}

package com.fy.service.impl;

import com.fy.service.AccountService;

public class AccountServiceImpl implements AccountService {

    @Override
    public void saveAccount() {
        System.out.println("执行了保存");
    }

    @Override
    public void updateAccount(int i) {
        System.out.println("执行了更新");
    }

    @Override
    public int deleteAccount() {
        System.out.println("执行了删除");
        return 0;
    }
}

package com.fy.utils;

public class logger {
    public void printLog(){
        System.out.println("Logger中的printLog开始记录日志了。。。");
    }
}

package com.fy.test;

import com.fy.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AOPTest {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        AccountService as = (AccountService)ac.getBean("accountService");
        as.saveAccount();
    }
}

XML配置:

<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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 配置Spring的IOC,把service对象配置进来-->
    <bean id="accountService" class="com.fy.service.impl.AccountServiceImpl"></bean>
    <bean id="logger" class="com.fy.utils.logger"></bean>
    <aop:config>
        <aop:aspect id="logAdvice" ref="logger">
            <aop:before method="printLog" pointcut="execution(public  void  com.fy.service.impl.AccountServiceImpl.saveAccount())"></aop:before>
        </aop:aspect>
    </aop:config>
</beans>

运行结果:
在这里插入图片描述
重点理解切入点表达式的过程写法,理解清楚既可以写出来

发布了25 篇原创文章 · 获赞 70 · 访问量 3225

猜你喜欢

转载自blog.csdn.net/qq_44706044/article/details/104085367