春のダーク馬:AOP_XML

1.春のXMLベースの設定手順AOP

ここに画像を挿入説明
一般的な言葉遣い
ここに画像を挿入説明


bean.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:aop="http://www.springframework.org/schema/aop"
       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">

    <!--配置spring的IOC,把service对象配置进来-->
    <bean id="accountService" class="com.jh.service.impl.AccountServiceImpl"></bean>

    <!--配置Logger类-->
    <bean id="logger" class="com.jh.utils.Logger"></bean>

    <!--配置AOP-->
    <aop:config>
        <!--配置切面-->
        <aop:aspect id="logAdvice" ref="logger">
            <!--配置通知的类型,并且建立通知方法和切入点方法的关联-->
            <aop:before method="printLog" pointcut="execution(* com.jh.service.impl.*.*(..))"></aop:before>
        </aop:aspect>
    </aop:config>
</beans>

2.サービス層、層utilsの、テストクラス

サービス:インタフェース

package com.jh.service;
/**账户的业务层接口*/
public interface IAccountService {
    //模拟保存账户
    void saveAccount();
    //模拟更新账户
    void updateAccount(int i);
    //模拟删除账户
    int deleteAccount();
}

サービス:実装クラス

package com.jh.service.impl;
import com.jh.service.IAccountService;
/**
 * 账户的业务层实现类
 * */
public class AccountServiceImpl implements IAccountService {
    @Override
    public void saveAccount() {
        System.out.println("执行了保存");
    }

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

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

utilsの:ログロガー(通知クラス)

package com.jh.utils;
/**
 * 用于记录日志的工具类,它里面提供了公共的代码
 * */
public class Logger {
    //用于打印日志,计划让其在切入点方法执行之前执行(切入点方法就是业务层方法)
    public void printLog(){
        System.out.println("Logger类中的printLog方法开始记录日志了。。。");
    }
}

AOPのテスト構成

package com.jh.test;
import com.jh.service.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**测试AOP的配置*/
public class AOPTest {
    public static void main(String[] args) {
        //1.获取容器
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取service bean对象
        IAccountService as=(IAccountService)ac.getBean("accountService");
        //3.执行方法
        as.saveAccount();
        as.deleteAccount();
        as.updateAccount(1);
    }
}

事前通知の結果:

通知bean在切入点方法执行之前执行(切面)
Logger类中的printLog方法开始记录日志了。。。(通知方法bean输出)
执行了保存            (切入点方法输出)
Logger类中的printLog方法开始记录日志了。。。
执行了删除
 Logger类中的printLog方法开始记录日志了。。。
执行了更新操作:1

公開された101元の記事 ウォン称賛15 ビュー6766

おすすめ

転載: blog.csdn.net/JH39456194/article/details/104434681