目标类:
package com.spring.aop;
public class HelloWorld {
public void get() {
System.out.println("Hello World!");
}
public void getTo(){
System.out.println("ni hao a!");
}
}
Before通知:
package com.spring.aop;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class SimpleBeforeAdvice implements MethodBeforeAdvice {
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println("Before Method: " + method.getName());
}
}
测试类:
package com.spring.aop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class ProxyFactoryBeanTest {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext(
"src/applicationContext.xml");
HelloWorld helloworldbean = (HelloWorld) context
.getBean("helloworldbean");
HelloWorld hellobean = (HelloWorld)context.getBean("hellobean");
HelloWorld helloworld = (HelloWorld)context.getBean("helloworld");
helloworldbean.get();
helloworldbean.getTo();
System.out.println("");
hellobean.get();
hellobean.getTo();
System.out.println("");
helloworld.get();
helloworld.getTo();
}
}
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="beanNameProxyCreator"
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>get*</value>
<value>*bean</value>

</list>
</property>
<property name="interceptorNames">
<list>
<value>advice</value>
</list>
</property>
</bean>
<bean id="helloworldbean" class="com.spring.aop.HelloWorld"></bean>
<bean id="hellobean" class="com.spring.aop.HelloWorld"></bean>
<bean id="helloworld" class="com.spring.aop.HelloWorld"></bean>
<bean id="advice" class="com.spring.aop.SimpleBeforeAdvice"></bean>
</beans>
关于配置文件疑问:他这是说对bean配置id的值是以'bean‘结尾会被代理,以get开头的方法都会被拦截。如果目标类中有returnXX方法及其他方法,我想让以return开头的方法也被拦截,该怎么配置呢? 

解决方案 »

  1.   

    用切入点的方式:
    <aop:config>
    <aop:advisor pointcut="execution(* com.zjm.study.dao.*.*(..))" advice-ref="transTxAdvice" /> <!-- 事务 -->
    <aop:advisor pointcut="execution(* com.zjm.study.dao.UserdbDAO.save(..))" advice-ref="exceptionAdvice" /> <!-- 拦截器 -->
    <aop:advisor pointcut="execution(* com.zjm.struts.action.*.*(..))" advice-ref="chkLoginAdvice" />
    </aop:config>execution(* com.zjm.study.dao.*.*(..))" ......
    第一个星表示返回类型
    后两个星表示某类某方法