AOP面向切面编程
1、导入pom坐标
<dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.4</version></dependency>
2、SpringConfig配置类
@Configuration
@ComponentScan("com.itheima")
@EnableAspectJAutoProxy
public class SpringConfig {}
- @Configuration 设置为配置类
- @ComponentScan 扫描路径
- @EnableAspectJAutoProxy 开启AOP切面编程
3、BookDao接口和实现类
public interface BookDao {void save();void update();
}@Repository
public class BookDaoImpl implements BookDao {public void save(){System.out.println("book save....");}public void update() {System.out.println("book update ...");}
}
4、AOP类
@Component
@Aspect
public class MyAdvice {//@Pointcut("execution(void com.itheima.dao.BookDao.update())")@Pointcut("execution(void com.itheima..BookDao.update())")private void pt(){}//前置@Before("pt()")public void before(JoinPoint jp){System.out.println(System.currentTimeMillis());}// 后置@After("pt()")public void after(){System.out.println("after .....");}//环绕 通知@Around("pt()")public Object around(ProceedingJoinPoint pjd) throws Throwable {System.out.println("before around....");// 有返回值需要返回下Object ret = pjd.proceed();System.out.println("after around....");return ret;}// 执行成功后通知@AfterReturning(value = "pt()", returning = "ret")public void afterReturning(Object ret){System.out.println("after returning ..."+ ret);}// 抛出一场后通知@AfterThrowing(value = "pt()", throwing = "err")public void afterThrowing(Throwable err){System.out.println("after throwing..."+ err);}
}
5、使用方法
public static void main(String[] args) {ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);BookDao bookDao = ctx.getBean(BookDao.class);bookDao.update();}