spring AOP的配置

我们通常会使用spring框架,使用配置xml文件或者注解方式来进行记录日志等操作

注解方式本人尚未学习,在这里仅仅记录使用xml文件时遇到的问题

beans 的头部需要加上

<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-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

</bean>

如果你的被代理对象方法有两个参数,而代理对象中的方法只需要一个参数,那么需要在xml文件中进行配置,不然会报错

错误信息:Pointcut is malformed: error at ::0 formal unbound in pointcut

被代理对象方法

public void login(String name,String password){
System.out.println(name + "登录,密码:" + password);
}

代理对象

public void loginBefore(String name){
System.out.println(name + "登录,已进行安全验证");
}

public void loginAfter(String name){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(name + "用户,登录时间" + sdf.format(new Date()));
}

对应配置文件

<aop:config>
<aop:pointcut expression="execution(* com.spring.homework1.UserLogin.*(..)) and args(name,..)"
id="userLoginPointCut" />
<aop:aspect ref="userLoginProxy">
<aop:before method="loginBefore" pointcut-ref="userLoginPointCut" arg-names="name"/>
<aop:after method="loginAfter" pointcut-ref="userLoginPointCut" /><!-- 当然这里不用写也是可以执行的,亲测可用 -->

</aop:aspect>
</aop:config>

原文地址:https://www.cnblogs.com/weiki/p/4129257.html