这是一个简单的spring aop的例子。
一:定义目标类
1>定义目标接口:IHelloWorldService
/**
* 定义目标接口
* */
public interface IHelloWorldService {
public void sayHello();
}
2>定义目标接口实现:HelloWorldService
/**
* 定义目标接口实现类
* */
public class HelloWorldService implements IHelloWorldService {
@Override
public void sayHello() {
System.out.println("============Hello World!");
}
}
二:定义切面支持类
/**
* 定义切面支持类
* */
public class HelloWorldAspect {
public void beforeAdvice(){
System.out.println("===========before Advice");
}
public void afterFinalAdvice(){
System.out.println("===========after finally advice");
}
}
三:在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"> <!-- 配置目标类 --> <bean id="helloWorldService" class="cn.javass.spring.chapter6.service.impl.HelloWorldService" /> <!-- 配置切面类 --> <bean id="aspect" class="cn.javass.spring.chapter6.aop.HelloWorldAspect" /> <aop:config> <aop:pointcut expression="execution(* cn.javass..*.*(..))" id="pointcut"/> <aop:aspect ref="aspect"> <aop:before method="beforeAdvice" pointcut-ref="pointcut"/> <aop:after method="afterFinalAdvice" pointcut="execution(* cn.javass..*.*(..))"/> </aop:aspect> </aop:config> </beans>
aop:pointcut表示切入点
aop:aspect表示切面
aop:before表示在point表达式中定义的方法之前执行after类似。可以直接引用声明的切入点,如before中。或者直接定义切入点,如after中