
首先在pom.xml中导入AOP织入的依赖包
aspectj aspectjweaver1.5.3
编写Service层
Service接口
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
ServiceImpl层
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("查询了一个用户");
}
}
编写log通知
前置通知
import java.lang.reflect.Method;
public class log implements org.springframework.aop.MethodBeforeAdvice {
///method :要执行的目标对象的方法
// args:参数
//target:目标对象
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+ method.getName()+"被执行了");
}
}
后置通知
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class Afterlog implements AfterReturningAdvice {
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行力" +method.getName()+"的方法,返回结果为"+returnValue);
}
}
编写applicationContext.xml文件
编写applicationContext.xml文件
import com.example.springaopdemo.Service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理代理的是接口
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
项目截图
运行结果
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)