基于xml的spring AOP配置主要有几个步骤:
1、创建切面类
编写自定义增强代码(如事务处理,日志等)
2、创建service
提供连接点
3、配置切面
在配置之前,先了解一些专业术语
连接点:被拦截的方法
切入点:拦截规则(符合规则被拦截的一类方法)
通知/增强:对拦截的方法添加自定义功能
切面:就是切面类,在其中自定义通知
编写切面类
//切面类
public class AspectClazz {
public void save() {
System.out.println("保存");
}
}
编写业务层代码
package my.service;
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;
import my.pojo.Student;
@RunWith(value=SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class StudentService {
@Autowired
private Student student;
@Test
public void test() {
System.out.println(student.getName());
}
}
在spring配置文件中配置
1、配置切面类
<!--配置切面类 -->
<bean name="aspectClazz" class="my.util.AspectClazz"></bean>
2、配置切面
<!-- 配置切面 -->
<aop:config>
<!--配置连接点 -->
<aop:pointcut expression="execution(* my..*.*(..))" id="pc"/>
<!--配置切面 -->
<aop:aspect ref="aspectClazz">
<aop:before method="save" pointcut-ref="pc"/>
</aop:aspect>
</aop:config>
注意配置拦截点需要设定拦截规则,
表达式语法:execution([修饰符] 返回值类型 包名.类名.方法名(参数))
写法说明:
全匹配方式:
public void cn.zj.service.impl.CustomerServiceImpl.saveCustomer()
访问修饰符可以省略
void com.zj.service.impl.CustomerServiceImpl.saveCustomer()
返回值可以使用*号,表示任意返回值
* com.zj.service.impl.CustomerServiceImpl.saveCustomer()
包名可以使用*号,表示任意包,但是有几级包,需要写几个*
* *.*.*.*.CustomerServiceImpl.saveCustomer()
使用..来表示当前包,及其子包
* com..CustomerServiceImpl.saveCustomer()
类名可以使用*号,表示任意类
* com..*.saveCustomer()
方法名可以使用*号,表示任意方法
* com..*.*()
参数列表可以使用*,表示参数可以是任意数据类型,但是必须有参数
* com..*.*(*)
参数列表可以使用..表示有无参数均可,有参数可以是任意类型
* com..*.*(..)
全通配方式:
* *..*.*(..)
来源:https://www.cnblogs.com/cdeelen/p/11000213.html