使用注解实现AOP
要切入的接口
package service;
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
其具体实现类
package service;
import service.UserService;
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("增加了一个用户");
}
@Override
public void delete() {
System.out.println("删除了一个用户");
}
@Override
public void update() {
System.out.println("更新了一个用户");
}
@Override
public void query() {
System.out.println("查询了一个用户");
}
}
切入方法:
package diy;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
//方式三:使用注解方式实现aop
//标注这个类是一个切面
@Aspect
public class AnnotationPointCut {
@Before("execution(* service.UserServiceImpl.*(..))")
public void before(){
System.out.println("========方法执行前======================");
}
@After("execution(* service.UserServiceImpl.*(..))")
public void after(){
System.out.println("==========方法执行后=========================");
}
}
xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--注册bean-->
<bean id="userService" class="service.UserServiceImpl"/>
<bean id="BeforeLog" class="log.BeforeLog"/>
<bean id="AfterLog" class="log.AfterLog"/>
<!--方式3-->
<bean id="annotationPointCut" class="diy.AnnotationPointCut"/>
<!--开启注解支持-->
<aop:aspectj-autoproxy/>
</beans>
测试代码:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.UserService;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理代理的是接口
UserService userService =(UserService) context.getBean("userService");
userService.add();
}
}