面向切面编程AOP

    技术2022-07-11  92

    连接点:程序执行流程中的某一个点,通常是一个方法执行的某一个时机。 通知:要加入到连接点中的某一段代码 切入点:一系列的连接点的集合 切面:切入点+通知 织入:将通知植入目标之中 首先我们要配置aop的xml文件 基本配置可以到spring官网的文档中查找 https://docs.spring.io/spring/docs/5.1.17.BUILD-SNAPSHOT/spring-framework-reference/core.html#aop-introduction-proxies

    <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"> <!--要被代理的类--> <bean id ="userDao" class="jee.pk4.UserDaoImpl"></bean> <bean id ="clientDao" class="jee.pk4.ClientDaoImpl"></bean> <!--当该标签的此属性为true时使用的时cglib代理,为false时使用的时jdk代理。 <aop:config proxy-target-class="true"> <!-- 这个bean保存通知内容 --> <bean id="daoAdvice" class="jee.pk4.DaoAdvice"></bean> <aop:config> <!-- 切面 --> <aop:aspect ref="daoAdvice"> <!-- 切入点 --> <!-- 切入点表达式 (任何返回值类型的,jee.pk4包中以impl为结尾的任何类的任何方法(任何参数,任何返回值))--> <aop:pointcut id="daoPointcut" expression="execution(* jee.pk4.*Impl.*(..))" /> <!-- 前置通知 --> <!--method属性的值是daoAdvice类中的前置通知方法名--> <--pointcut-ref属性指向的是要放入通知的切入点--> <aop:before pointcut-ref="daoPointcut" method="before"/> </aop:aspect> </aop:config> </beans>

    通知类:

    public class DaoAdvice { public boolean before() { System.out.println("前置通知"); return true; } }

    main方法:

    public class App { public static void main(String[] args) { ApplicationContext ac=new ClassPathXmlApplicationContext("beans_pk1.xml"); UserDao p1=ac.getBean("userDao",UserDao.class);//得到的是代理对象 ClientDao p2=ac.getBean("clientDao",ClientDao.class); p1.insert(); p2.insert(); } }

    结果:

    Processed: 0.016, SQL: 9