SSM[spring] 基于注解的AOP使用 发表于 2023-12-30 | 分类于 SSM 示例代码[AccountServiceImp]1234567891011121314151617181920212223package com.gphper.Imp;import com.gphper.IAccountService;import org.springframework.stereotype.Service;@Service("accountService")public class AccountServiceImp implements IAccountService { @Override public void saveAccount() { System.out.println("保存账号成功"); } @Override public void updateAccount(int i) { System.out.println("更新账号id"+i); } @Override public void deleteAccount() { System.out.println("删除账号成功"); }} [LogUtil]1234567891011121314151617181920212223242526272829303132333435package com.gphper.utils;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.springframework.stereotype.Component;@Component("log")@Aspectpublic class LogUtil { @Pointcut("execution(* *..*.*(..))") public void ptr1(){}; public void printLog(){ System.out.println("打印日志输出········"); } @Around("ptr1()") public Object aroundNotify(ProceedingJoinPoint pjp){ Object valObj = null; try { Object[] args = pjp.getArgs(); System.out.println("通知前····"); valObj = pjp.proceed(args); System.out.println("通知后····"); }catch (Throwable e){ } return valObj; }} [bean.xml]12345678910111213141516<?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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://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"> <context:component-scan base-package="com.gphper"></context:component-scan> <aop:aspectj-autoproxy></aop:aspectj-autoproxy></beans> [Test.java]1234567891011121314151617181920package com.test;import com.gphper.IAccountService;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class ApoTest { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); IAccountService as = (IAccountService)ac.getBean("accountService"); as.saveAccount(); }} Spring中的事务处理