目录
AOP(面向切面编程):一种编程范式,指导开发者如何组织程序结构。
作用:在不改变原始设计的基础上进行功能增强。
如以下代码:如何再不改变此类的基础上,使后三个方法达到与save方法同样的效果?
public class BookDaoImpl implements BookDao {
public void save(){
Long startTime = System.currentTimeMillis();
for(int i = 0;i < 10000;i++)
System.out.println("book dao save...");
Long endTime = System.currentTimeMillis();
Long totalTime = endTime-startTime;
System.out.println(totalTime + "ms");
}
public void update(){
System.out.println("book dao update...");
}
public void delete(){
System.out.println("book dao delete...");
}
public void select(){
System.out.println("book dao select...");
}
}
pom.xml文件加入以下坐标,注意加入后刷新maven。
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.9</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>
@Repository
public class BookDaoImpl implements BookDao {
public void save(){
System.out.println(System.currentTimeMillis());
System.out.println("book dao save...");
}
public void update(){
System.out.println("book dao update...");
}
}
public class MyAdvice {
public void method(){
System.out.println(System.currentTimeMillis());
}
}
切入点是匹配连接点的式子
public class MyAdvice {
@Pointcut("execution(void com.spring.dao.BookDao.update())")
private void pt(){}
}
public class MyAdvice {
@Pointcut("execution(void com.spring.dao.BookDao.update())")
private void pt(){}
@Before("pt()")
public void method(){
System.out.println(System.currentTimeMillis());
}
}
加入@Component和@Aspect
切面是描述通知与切入点的对应关系
@Component
@Aspect
public class MyAdvice {
@Pointcut("execution(void com.spring.dao.BookDao.update())")
private void pt(){}
@Before("pt()")
public void method(){
System.out.println(System.currentTimeMillis());
}
}
@EnableAspectJAutoProxy开启Spring对AOP注解驱动支持
@Configuration
@ComponentScan("com.spring")
@EnableAspectJAutoProxy
public class SpringConfig {
}