今天学到了面向切面编程aop的第二种方法 自定义切面类
导入依赖的步骤以及ApplicationContext.xml的步骤和上一种方法一致
依赖如下
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
ApplicationContext.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
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="beforeLog" class="com.zyy.log.BeforeLog"/>
<bean id="afterLog" class="com.zyy.log.AfterLog"/>
<bean id="userServiceImpl" class="com.zyy.service.UserServiceImpl"/>
<bean id="diy" class="com.zyy.log.Log"/>
<!-- <aop:config>-->
<!-- <aop:pointcut id="pointcut" expression="execution(* com.zyy.service.UserServiceImpl.*(..))"/>-->
<!-- <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>-->
<!-- <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>-->
<!-- </aop:config>-->
<aop:config>
<aop:aspect ref="diy">
<aop:pointcut id="point" expression="execution(* com.zyy.service.UserServiceImpl.*(..))"/>
<aop:after method="frist" pointcut-ref="point"/>
<aop:before method="last" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
</beans>
上面注释掉的是上一种方法的aop 可以和这种方法对比学习
关于这段代码的理解
<aop:config>
<aop:aspect ref="diy">
<aop:pointcut id="point" expression="execution(* com.zyy.service.UserServiceImpl.*(..))"/>
<aop:after method="frist" pointcut-ref="point"/>
<aop:before method="last" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
这里面的pointcut和上一种方法一样是切入点 id是设置的切入点的名字,后面的表达式则是规定了哪些方法执行前后会触发这个。
和上一种方法不一样,这种方法的触发时间是通过<aop:after或者<aop:before来设置的 上一种则是通过提前创建好了对象,这两个对象实现了两个接口 用接口里面的方法来控制触发时间
测试
import com.zyy.service.USerService;
import com.zyy.service.UserServiceImpl;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) throws BeansException {
ApplicationContext Context = new ClassPathXmlApplicationContext("applicationContext.xml");
USerService userService = Context.getBean("userServiceImpl", USerService.class);
userService.update();
}
}