项目结构大致如下(没展示则没使用):
第一步:编写pom(因为aop是spring的内置,所以不需要导)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>spring-test</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
第二,编写bookdaoimp:
package com.wxy.dao.impl;
import com.wxy.dao.BookDao;
import org.springframework.stereotype.Repository;
import java.util.*;
@Repository
public class BookDaoImpl implements BookDao {
@Override
public void save() {
System.out.println(System.currentTimeMillis());
System.out.println("save....");
}
@Override
public void update() {
System.out.println("bookDao is updating");
}
}
第三,编写bookdao:
package com.wxy.dao;
public interface BookDao {
public void save();
public void update();
}
第四,编写一个aop的说明,文件,告诉spring你要使用哪个切点,你要使用什么方法作为公用方法:
package com.wxy.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
@Aspect
public class MyAdvice {
@Pointcut("execution(void com.wxy.dao.BookDao.update())")
private void pt(){}
@Before("pt()")
public void methon(){
System.out.println(System.currentTimeMillis());
}
}
第五,编写spring配置文件(有了这个注解才能支持@Aspect等相关的一系列AOP注解的功能):
package com.wxy.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan("com.wxy")
@EnableAspectJAutoProxy
public class SpringConfig {
}
第六,编写测试类:
package com.wxy;
import com.wxy.config.SpringConfig;
import com.wxy.dao.BookDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App2 {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
BookDao bookDao = ctx.getBean(BookDao.class);
bookDao.update();
}
}
执行测试类,可得以下结果:
可以看到update本来没有
System.out.println(System.currentTimeMillis());
语句,但是却执行了该方法,可以说明,在aop的帮助下,在其添加了一个method方法输出了该语句。