1、导入Aop相关坐标,Spring默认支持Aop开发spring-context坐标依赖spring-aop坐标
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
2、定义dao接口和实现类
package com.itheima.service.impl;
import com.itheima.service.UserService;
import org.springframework.stereotype.Service;
@Service //实现类一定要交给spring管理
public class UserServiceImpl implements UserService {
@Override
public void selectById() {
System.out.println(System.currentTimeMillis());
System.out.println("selectById");
}
@Override
public void upDataById() {
System.out.println("upDataById");
}
}
3、定义通知类,制定通知 4、定义切入点 5、绑定切入点与通知关系,并指定添加到原始连接的具体执行位置 6、定义通知受spring容器管理,并定义当前类为切面类
package com.itheima.aop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Component //定义通知受spring管理
@Aspect //定义当前类为切面类
public class Aop {
@Pointcut("execution(void com.itheima.service.UserService.upDataById())")//定义切入点 参数表示方法是com.itheima.service.UserService.upDataById() 无返回值
public void pt(){}//说明切入点依托一个不具有实际意义的方法,即无参数,无返回值,方法体无逻辑
@Before("pt()")//绑定切入点与通知关系,并指定添加到原始连接的具体执行位置
public void method(){
System.out.println(System.currentTimeMillis());//通知
}
@Pointcut("execution(void com.itheima.Test.*())") //通配符*表示Test中所有方法
public void pp(){}
@Before("pp()")
public void method2(){
System.out.println(System.currentTimeMillis());
}
}
7、开启spring对Aop注解驱动支持
package com.itheima.config;
import org.springframework.context.annotation.*;
@Configuration //定义当前类为配置类
@EnableAspectJAutoProxy //驱动支持Aop注解
@ComponentScan("com.itheima") //扫描路径包下的bean
@PropertySource("classpath:jdbc.properties") //加载properties文件
@Import({JdbcConfig.class, MybatisConfig.class}) //导入管理第三方bean
public class SpringConfig {
}