springAOP对方法进行增强
1.导入AOP所用的的jar包
![请添加图片描述](https://img-blog.csdnimg.cn/5c917aa3654c46d5921b035e411053fe.png)
2.创建UserService接口和UserServiceImpl实现类对增删改查方法的封装
public interface UserService {
void add();
void delete();
void update();
void select();
}
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("add");
int i=1/0;
}
@Override
public void delete() {
System.out.println("delete");
}
@Override
public void update() {
System.out.println("update");
}
@Override
public void select() {
System.out.println("select");
}
}
3.创建MyAdvice类添加增强的方法
package com.aop;
import org.aspectj.lang.ProceedingJoinPoint;
public class MyAdvice {
public void before() {
System.out.println("before");
}
public void after() {
System.out.println("after");
}
public void afterReturning() {
System.out.println("afterReturning");
}
public void afterThrowing() {
System.out.println("afterThrowing");
}
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("around before");
Object proceed = pjp.proceed();
System.out.println("around after");
return proceed;
}
}
4.配置applicationContext.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
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-4.3.xsd">
<!-- 目标对象 -->
<bean name="userService" class="com.service.UserServiceImpl"></bean>
<bean name="MyAdvice" class="com.aop.MyAdvice"></bean>
<aop:config>
<!-- 切入点 expression 切入点表达式 可以配置要增强的方法
public void com.service.UserServiceImpl.save()
* com.service.*ServiceImpl.*(..)
id 就是唯一标识
-->
<!--切入点表达式类似将其中的方法当作一个切面,后面的增强方法将会调用对应的切面-->
<aop:pointcut expression="execution(* com.service.*ServiceImpl.*(..))" id="servicePc"/>
<aop:aspect ref="MyAdvice">
<!--增强方法-->
<aop:before method="before" pointcut-ref="servicePc"/>
<aop:after method="after" pointcut-ref="servicePc"/>
<aop:after-throwing method="afterThrowing" pointcut-ref="servicePc"/>
<aop:after-returning method="afterReturning" pointcut-ref="servicePc"/>
<aop:around method="around" pointcut-ref="servicePc"/>
</aop:aspect>
</aop:config>
</beans>
5.创建测试类
package com.Test;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class spring_aop_test {
@Resource(name = "userService")
UserService us;
@Test
public void test01() {
us.add();
}
}