AspectJ实现AOP(xml配置方式)

【例子】用户登录添加日志功能

一、导jar包

项日结构如下:



二、创建相关类

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;
public class MyAspect {
	//此方法作为前置通知
	public void before(JoinPoint joinPoint){
		//获取被调用的类名
		String targetClassName=joinPoint.getTarget().getClass().getName();
		//获取被调用的方法名
		String targetMethodName=joinPoint.getSignature().getName();
		//日志格式字符串
		System.out.println("【前置通知】"+targetClassName+"类的"+targetMethodName+"方法开始执行。");
	}
}

测试类

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>
<aop:config>
	<!-- 配置切面 -->
	<aop:aspect ref="myAspect">
		<!-- 配置切入点 对com.aop.User.login方法进行拦截 -->
		<aop:pointcut expression="execution(* com.aop.User.login(..))" id="myPointcut"/>
		<!-- 将MyAspect的before指定为前置通知-->
		<aop:before method="before" pointcut-ref="myPointcut"/>
	</aop:aspect>
</aop:config>
</beans>

运行结果:


猜你喜欢

转载自blog.csdn.net/dwenxue/article/details/80831642