AspectJ 是一个 AOP 的具体实现框架。AOP(Aspect Oriented Programming)即面向切面编程,可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。AspectJ不但可以通过预编译方式(CTW)和运行期动态代理的方式织入切面,还可以在载入(Load Time Weaving, LTW)时织入。AspectJ 扩展了Java,定义了一些专门的AOP语法。
1 pom配置maven插件:
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.10</version>
<configuration>
<complianceLevel>1.8</complianceLevel>
<source>1.8</source>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
2 增加pom依赖
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
3 编写被注入的sevice类
public interface SampleService {
public String getName(String name);
}
public class SampleServiceImpl implements SampleService {
@Override
public String getName(String name) {
return name;
}
}
4 编写切面类
@Aspect
public class SampleAspect {
/**
* 切入点:SampleService继承树中所有方法。
*/
@Pointcut("execution(* com.li.service.impl..*(..))")
public void methodePointCut(){
}
@Before("methodePointCut()")
public void monitor(JoinPoint joinPoint) throws Throwable{
System.out.println(joinPoint.getStaticPart());
}
@After("methodePointCut()")
public void monitor2(JoinPoint joinPoint) throws Throwable{
System.out.println(joinPoint.getStaticPart());
}
}
5 编写测试用例
public class SampleTest {
@Test
public void testAspect(){
SampleService sampleService = new SampleServiceImpl();
System.out.println(sampleService.getName("aaa"));
}
}
6 运行测试
execution(String com.li.service.impl.SampleServiceImpl.getName(String))
execution(String com.li.service.impl.SampleServiceImpl.getName(String))
aaa
7 切面单独项目提供
切面所在的pom配置:
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.10</version>
<configuration>
<complianceLevel>1.8</complianceLevel>
<source>1.8</source>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
被切入的项目引用切面项目
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.10</version>
<configuration>
<complianceLevel>1.8</complianceLevel>
<source>1.8</source>
<aspectLibraries>
<aspectLibrary>
<groupId>com.li</groupId>
<artifactId>aspectJ2</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>