1、maven目录结构
2、创建接口UserService,在接口中定义方法
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
3、spring 配置文件applicationContext.xml,开启注解扫描
<?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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!-- 扫描包-->
<context:component-scan base-package="com.szx"/>
<!-- 开启aspect生成代理对象
为true则是基于类的代理将起作用(需要cglib库),
为false或者省略这个属性,则标准的JDK 基于接口的代理将起作用 -->
<aop:aspectj-autoproxy proxy-target-class="false"/>
</beans>
4、创建接口实现类UserServiceImpl,实现方法
@Component
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("add方法");
}
public void delete() {
System.out.println("delete方法");
}
public void update() {
System.out.println("update方法");
}
public void query() {
System.out.println("query方法");
}
}
5、增强类AnnotationPointcut ,对UserServiceImpl类进行扩展
@Aspect// 增强类
@Component
public class AnnotationPointcut {
//相同切入点抽取
@Pointcut("execution(* com.szx.service.UserServiceImpl.*(..))")
public void pointcut(){}
@Before("pointcut()")
public void before(){
System.out.println("before。。。");
}
@After("pointcut()")
public void after(){
System.out.println("after。。。");
}
@Around("pointcut()")
public void around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前");
Object proceed = pjp.proceed();
System.out.println("环绕后");
}
//后置通知(返回通知)
@AfterReturning("pointcut()")
public void afterReturning(){
System.out.println("afterReturning....");
}
//异常通知
@AfterThrowing(value = "pointcut()")
public void afterThrowing() {
System.out.println("afterThrowing.........");
}
}
6、测试类MyTest
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userServiceImpl", UserService.class);
userService.update();
}
}
这里主要测试配置文件applicationContext.xml的注解与测试类中context.getBean如何搭配使用
<aop:aspectj-autoproxy proxy-target-class="false"/>
UserService userService = context.getBean("userServiceImpl", UserService.class);
Note:
1、spring版本5,必须使用注解<aop:aspectj-autoproxy proxy-target-class=“false”/>
2、当proxy-target-class=“true”,基于类的代理,在getBean第二个参数中可以使用接口UserService.class,也可以使用类UserServiceImpl.class
3、当proxy-target-class="false"或者不写这个配置,这里必须有aop:aspectj-autoproxy/,否则报错,这是基于jdk接口的代理,只能在getBean第二个参数中可以使用接口UserService.class