我尝试应用MethodBeforeAdvice但无法执行此操作。我无法弄清楚它有什么问题。请帮帮我。
//Interface
package org.mycode;
public interface IHello {
boolean authenticate(String input);
}
//Class on which advice need to be applied
package org.mycode;
public class HelloImpl implements IHello {
@Override
public boolean authenticate(String input) {
System.out.println("authecated successfully");
System.out.println(System.currentTimeMillis());
System.out.println(input);
return true;
}
}
}
//Advice class
package org.mycode;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class MethodAdvice1 implements MethodBeforeAdvice {
@Override
public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
System.out.println("checking for authentication of the caller");
System.out.println(arg0.getName());
System.out.println(arg0.getDeclaringClass().getName());
System.out.println(arg1);
System.out.println("time start: " + System.currentTimeMillis());
}
}
//Client for the Adviced class
package org.mycode;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class AdviceManager {
public static void main(String[] args) {
ClassPathResource cp = new ClassPathResource("org/mycode/config.xml");
BeanFactory factory = new XmlBeanFactory(cp);
HelloImpl hil = (HelloImpl) factory.getBean("myClass");
System.out.println(hil.authenticate("AdvicedMethod"));
}
}
//Config file
config.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean id="advice1" class="org.mycode.MethodAdvice1"></bean>
<bean id="myClass" class="org.mycode.HelloImpl"></bean>
<bean id="aspect1"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice" ref="advice1"></property>
<property name="pattern">
<value>.*</value>
</property>
</bean>
<bean id="advicedHello" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>org.mycode.IHello</value>
</property>
<property name="target" ref="myClass" />
<property name="interceptorNames">
<list>
<value>aspect1</value>
</list>
</property>
</bean>
</beans>
运行时的输出 信息:从类路径资源[org / mycode / config.xml]加载XML bean定义 验证成功 1467340328875 AdvicedMethod 真