这几天在看Spring Aop的东西,做了一个简单的小例子:
public interface IHello {
public String hello(String name) ;
}
public class HelloSpeaker implements IHello {
public String hello(String name) {
String hello = " Hello " + name ;
System.out.println( hello );
return hello ;
}
}
上面的是接口和实现类,也就是需要被AOP处理的类,也就是Target.
下面这个类,是AOP中Aspect,切入类,我采用的是,afterReturn类型
public class AfterReturnExample {
public void profile( Object retVal ) {
System.out.println(" the result " + retVal );
System.out.println(" after return ");
}
}
下面是spring的配置文件:
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<aop:config>
<aop:aspect id="beforeExample" ref="afterReturnExample">
<aop:after-returning pointcut="execution(* com.ultrapower.demo.aop.*.*(..))" method="profile" returning="retVal"/>
</aop:aspect>
</aop:config>
<bean id="hello" class="com.ultrapower.demo.aop.HelloSpeaker"></bean>
<bean id="afterReturnExample" class="com.ultrapower.demo.aop.before.AfterReturnExample"></bean>
</beans>
下面是测试类:
public class Test {
public static void main(String [] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("aop/applicationContext.xml");
IHello hello = (IHello) context.getBean("hello");
hello.hello("zzx") ;
}
}
刚刚开始的时候出现了一个错误:
- Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1808199: defining beans
[org.springframework.aop.config.internalAutoProxyCreator,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,hello,
afterReturnExample]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.s
pringframework.aop.aspectj.AspectJPointcutAdvisor#0': Instantiation of bean failed; nested exception is org.springframew
ork.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.aop.aspectj.AspectJPointcutA
dvisor]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: warning no match for this
type name: com.ultrapower.demo.aop [Xlint:invalidAbsoluteTypeName]
这个错误主要是 pointcut配置的错误,修改之后就可以了:pointcut="execution(* com.ultrapower.demo.aop.*.*(..))"