上一篇谢了动态代理,这篇写spring中的一个重要特征AOP,来进行spring的面向切面编程.
首先配置pom.xml文件
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
2,我们先写一个接口,里面还是正常的增删改查方法
3,写这个接口的实现类,并实现接口的方法
package User;
public class UserDaoImpl implements UserDao {
@Override
public void add() {
System.out.println("实现了add方法");
}
@Override
public void delete() {
System.out.println("实现了delete方法");
}
@Override
public void update() {
System.out.println("实现了update方法");
}
@Override
public void query() {
System.out.println("实现了query方法");
}
}
4,然后我们可以写一个类继承MethodBeforeAdvice接口,再写一个类继承AfterReturningAdvice接口(前置后置通知),这时候我们的xml配置文件只需要这样写:
<bean id="before" class="AOP.before"></bean>
<bean id="after" class="AOP.After"></bean>
<bean id="Impl" class="User.UserDaoImpl"></bean>
<bean id="diy" class="Diy.diy"></bean>
<aop:config>
<aop:pointcut id="pointcutaop" expression="execution(* User.UserDaoImpl.*(..))"/>
<aop:advisor advice-ref="before" pointcut-ref="pointcutaop"></aop:advisor>
<aop:advisor advice-ref="after" pointcut-ref="pointcutaop"></aop:advisor>
</aop:config>
5,如果我们自定义类,里面注解写方法,那么我们的xml配置文件这样写:
<aop:config>
<aop:aspect ref="diy">
<aop:pointcut id="pointcutdiy" expression="execution(* User.UserDaoImpl.*(..))"/>
<aop:before method="before1" pointcut-ref="pointcutdiy"></aop:before>
<aop:after method="after1" pointcut-ref="pointcutdiy"></aop:after>
</aop:aspect>
</aop:config>
6,测试
import User.UserDao;
import User.UserDaoImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("aop.xml");
UserDao impl = (UserDao) applicationContext.getBean("Impl");
impl.add();
}
}