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>

运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云淡风轻58

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值