基于@AspectJ注解的AOP实现
程序员文章站
2022-07-12 14:10:11
...
【例子】用户登录添加日志功能
一、项目结构
二、创建相关类
User类
package com.aop;
public class User {
private String userName;
public User(){}
public User(String userName) {
super();
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void login(){
System.out.println("【"+this.userName+"】"+"用户正在登录。");
}
}
MyAspect类
package com.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
//日志切面
@Aspect
public class MyAspect {
@Pointcut("execution(* com.aop.User.login(..))")
//定义切入点名字
private void allMethod(){}
//定义前置通知
@Before("allMethod()")
public void before(JoinPoint joinPoint){
//获取被调用的类名
String targetClassName=joinPoint.getTarget().getClass().getName();
//获取被调用的方法名
String targetMethodName=joinPoint.getSignature().getName();
//日志格式字符串
System.out.println("【前置通知】"+targetClassName+"类的"+targetMethodName+"方法开始执行。");
}
}
Test类
package com.aop;
import org.springframework.aop.BeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
//加载SpringAop.xml配置
ApplicationContext context=new ClassPathXmlApplicationContext("SpringAop.xml");
//获取配置中的user实例
User user=(User) context.getBean("user");
user.setUserName("马向林");
user.login();
}
}
三、配置SpringAop.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 http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->
<bean id="user" class="com.aop.User"></bean>
<bean id="myAspect" class="com.aop.MyAspect"></bean>
<!-- 开启基于@Aspectj切面的注解处理器 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
运行结果: