1.AdviceMethods.java
package com.bijian.study.spring.aop.schema;
public class AdviceMethods {
public void preGreeting() {
System.out.println("--how are you!--");
}
}
2.beans.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-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <aop:config proxy-target-class="true"> <aop:aspect ref="adviceMethods"> <!-- 配置指定的一个类 --> <!-- <aop:before pointcut="target(com.baobaotao.NaiveWaiter) or target(com.baobaotao.NaughtyWaiter) and execution(* greetTo(..))" method="preGreeting"/> --> <!-- 配置指定的多个类 --> <!-- <aop:before pointcut="target(com.baobaotao.NaiveWaiter) or target(com.baobaotao.NaughtyWaiter) and execution(* greetTo(..))" method="preGreeting"/> --> <!-- 配置指定的接口,此接口的所有实现类都被切面化了 --> <aop:before pointcut="target(com.bijian.study.spring.aop.Waiter) and execution(* greetTo(..))" method="preGreeting"/> </aop:aspect> </aop:config> <bean id="adviceMethods" class="com.bijian.study.spring.aop.schema.AdviceMethods"/> <bean id="naiveWaiter" class="com.bijian.study.spring.aop.NaiveWaiter"/> <bean id="naughtyWaiter" class="com.bijian.study.spring.aop.NaughtyWaiter"/> </beans>
3.Waiter接口
package com.bijian.study.spring.aop;
public interface Waiter {
public void greetTo(String name);
}
4.NaiveWaiter.java
package com.bijian.study.spring.aop;
public class NaiveWaiter implements Waiter{
@Override
public void greetTo(String name) {
System.out.println("NavieWaiter:greet to " + name);
}
}
5.NaughtyWaiter.java
package com.bijian.study.spring.aop;
public class NaughtyWaiter implements Waiter{
@Override
public void greetTo(String name) {
System.out.println("NaughtyWaiter:greet to " + name);
}
}
6.测试类Test.java
package com.bijian.study.spring.aop.schema;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.bijian.study.spring.aop.Waiter;
public class Test {
public static void main(String[] args) {
String configPath = "com/bijian/study/spring/aop/schema/beans.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath);
Waiter naiveWaiter = (Waiter)ctx.getBean("naiveWaiter");
Waiter naughtyWaiter = (Waiter)ctx.getBean("naughtyWaiter");
naiveWaiter.greetTo("John");
naughtyWaiter.greetTo("Tom");
}
}
运行结果:
--how are you!-- NavieWaiter:greet to John --how are you!-- NaughtyWaiter:greet to Tom