继续以上一篇文章的例子来演示。
上篇文章中创建了两个切点(但两个切点是相同的“execution(* lzj.com.spring.aop.ArithmeticCalculator.*(..))”),如果以后,创建的切点越来越多的话,在做切点时,势必会增加程序的负担,下面就显示合并切点的例子。
代码实例
本次实例核心人物是计算两个数字的加减乘除,但是我要在计算的前后分别打印日志,把打印日志放在切面程序里面。本实例采用spring4.0版本,在新建立一个工程时,需要导入一下几个jar包:
com.springsource.NET.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-logging-1.1.1.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
1、建立一个接口
该ArithmeticCalculator 接口定义了两个数字的加减乘除法
package lzj.com.spring.aop;
//服务接口
public interface ArithmeticCalculator {
int add(int i, int j);
int sub(int i, int j);
int mul(int i, int j);
int div(int i, int j);
}
2、创建该接口的实现类
package lzj.com.spring.aop;
import org.springframework.stereotype.Component;
//一定要该注解,否则无法装载arithmeticCalculator这个bean到容器中
@Component("arithmeticCalculator")
public class ArithmeticCalculatorIml implements ArithmeticCalculator {
@Override
public int add(int i, int j) {
int result = i + j;
return result;
}
@Override
public int sub(int i, int j) {
int result = i - j;
return result;
}
@Override
public int mul(int i, int j) {
int result = i * j;
return result;
}
@Override
public int div(int i, int j) {
int result = i / j;
return result;
}
}
3、创建切面程序
该切面程序主要负责打印加减程序前后的日志
package lzj.com.spring.aop;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component //一定要加上此注解,否则找不到该代理Bean
public class LogProxy {
//创建Pointcut注解,用来合并后面类似的注解
@Pointcut("execution(* lzj.com.spring.aop.ArithmeticCalculator.*(..))")
public void performance(){
}
@Before("performance()")
public void beforMethod(){
System.out.println("在调用前……");
}
@After("performance()")
public void afterMethod(){
System.out.println("在调用之后……");
}
}
4、创建配置类
核心代码和切面程序都创建完毕了,还要对他们配置,才能在容器中发现他们。
package lzj.com.spring.aop;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
//配置类,以便能够发现容器中的bean
@Configuration
@ComponentScan //配置该注解,在容器中能发现装载的bean
@EnableAspectJAutoProxy //配置该注解,激活切面程序
public class AnnotationConfig {
}
5、创建测试类
package lzj.com.spring.aop;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AnnotationConfig.class);
ArithmeticCalculator arithmetic = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator");
int resultAdd = arithmetic.add(3, 2);
System.out.println("add的输出结果为:" + resultAdd);
}
}
输出结果为:
在调用前……
在调用之后……
add的输出结果为:5
本例子只是在修改上一篇文章的切面程序中的的切点部分,增加了Pointcut注解,用来合并切点,其它均未改变。