案例之前,我們先了解一下spring的幾個術語
導入需要的依賴:pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>spring-test-taskFour</artifactId> <groupId>com.lw</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>mybatis-spring-aop2</artifactId> <dependencies> <!--切面需要的依賴--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> </dependency> <!--spring依賴--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <!--測試依賴--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> </dependencies> </project>
切面類:
package com.aspect; public class LogImpl { //通知 public void beforeInsert(){ System.out.println("beforeInsert as LogImpl"); } }
目標類:
package com.target; public class StudentDaoImpl { //此類沒有實現接口,所以使用cglib代理的方法創建出aop代理 //實現接口會使用jdk代理方法創建aop代理 //連接點方法若是加了final修飾符的話,無法創建aop代理 //連接點 public void insert(){ System.out.println("insert as StudentDaoImpl"); } }
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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <!--先把bean創建出來--> <bean id="log" class="com.aspect.LogImpl"></bean> <bean id="studentDao" class="com.target.StudentDaoImpl"></bean> <!--以aop:config開始配置--> <aop:config> <!--配置目標類,expression是切點表達式,這里的意思是匹配com.target包 的StudentDaoImpl類的所有方法,第一個*號的意思是所有方法返回值,包括void--> <aop:pointcut id="studentPointcut" expression="execution(* com.target.StudentDaoImpl.*())"/> <!--配置切點類--> <aop:aspect id="logAspect" ref="log"> <!--配置連接點,和目標--> <aop:before method="beforeInsert" pointcut-ref="studentPointcut"/> </aop:aspect> </aop:config> </beans>
測試類:
package com.test; import com.target.StudentDaoImpl; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestAspect { @Test public void test_Aspect(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); StudentDaoImpl studentDao = context.getBean("studentDao",StudentDaoImpl.class); studentDao.insert(); } }
測試結果:
BeforeInsert as LogImpl
insert as StudentDaoImpl
可以看到我們的連接點方法成功切入了目標類。