AspectJ是一个基于Java语言的AOP框架,它提供了强大的AOP功能。Spring 2.0以后,Spring AOP引入了对AspectJ的支持,并允许直接使用AspectJ进行编程,而Spring自身的AOP API也尽量与AspectJ保持一致。新版本的Spring框架,也建议使用AspectJ来开发AOP。
使用AspectJ实现AOP有两种方式:一种是基于XML的声明式AspectJ,另一种是基于注解的声明式AspectJ。
jar包
package com.itcast.factorybean;
public interface CustomerService {
void save();
void delete();
}
package com.itcast.factorybean;
public class CustomerServiceImpl implements CustomerService{
public void save() {
System.out.println(“客户 保存成功…”);
}
@Override
public void delete() {
System.out.println("客户删除成功");
}
}
package com.itcast.factorybean;
public class MyAspect {
public void before() {
System.out.println(“第一个前置通知”);
}
}
package com.itcast.factorybean;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations=“classpath:applicationContext-aspect.xml”)
public class SpringTest {
@Autowired
private CustomerService customerService;
@Test
public void test() {
customerService.save();
customerService.delete();
}
}
<?xml version="1.0" encoding="UTF-8"?><bean id="customerService" class="com.itcast.factorybean.CustomerServiceImpl"></bean>
<bean id="myAspect" class="com.itcast.factorybean.MyAspect"></bean>
<!-- 1 切入点 -->
<aop:config>
<aop:pointcut expression="bean(*Service)" id="mycut" />
<!-- 2 切面类 -->
<aop:aspect ref="myAspect">
<aop:before method="before" pointcut-ref="mycut"/>
</aop:aspect>
</aop:config>
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190428224843554.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDE3NDUzNg==,size_16,color_FFFFFF,t_70)