两种AOP实现方式
- Schema-based
每个通知都需要实现接口或类每个通知都需要实现接口或类,配置spring文件在<aop:config> - AspectJ
每个通知不需要实现接口或类,配置spring文件在<aop:config>的子标签<aop:aspect>
1. Schema-based
1 导入jar包
注意是钱前三个包
2 新建通知类
--------------前置通知-----------------
实现MethodBeforeAdvice接口
重写before方法
public class BeforeAdvice implements MethodBeforeAdvice{
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的" + method.getName()+" 方法被执行");
}
}
---------------后置通知------------------
实现AfterReturningAdvice接口
重写afterReturning方法
public class AfterAdvice implements AfterReturningAdvice{
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
// TODO Auto-generated method stub
System.out.println(target.getClass().getName()+"的"+method.getName()+" 方法被执行,其返回值"+returnValue);
}
}
3 配置spring配置文件
3.1 引入aop命名空间
-------- 引入
xmlns:aop=“http://www.springframework.org/schema/aop”
xsi:schemaLocation=中加入
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"
3.2 配置通知类的<bean>
<?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
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="user" class="cn.lee.service.UserServiceImpl"/>
<bean id="beforeAdvice" class="cn.lee.log.BeforeAdvice "/>
<bean id="afterAdvice" class="cn.lee.log.AfterAdvice"/>
<aop:config>
<!--表示cn.lee.service包下所有的类的所有方法都当做切点-->
<aop:pointcut expression="execution(* cn.lee.service.*.*(..))" id="pointcut"/>
<aop:advisor advice-ref="beforeAdvice" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterAdvice " pointcut-ref="pointcut"/>
</aop:config>
</beans>
3.3 切面方法
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("增加用户");
}
@Override
public void update() {
System.out.println("修改用户");
}
}
3.4 测试方法
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
UserService userService = (UserService) ac.getBean("user");
userService.add();
}
}
输出
cn.lee.service.UserServiceImpl的add 方法被执行
增加用户
cn.lee.service.UserServiceImpl的add 方法被执行,其返回值null