springaop使用很简单,
一,配置文件
在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:context="http://www.springframework.org/schema/context" xmlns:jms="http://www.springframework.org/schema/jms" xmlns:amq="http://activemq.apache.org/schema/core" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.8.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 激活组件扫描功能,在包cn.ysh.studio.spring.aop及其子包下面自动扫描通过注解配置的组件 --> <context:component-scan base-package="main.java.com.springaop"/> <!-- 激活自动代理功能 --> <aop:aspectj-autoproxy proxy-target-class="true"/> <!-- 用户服务对象 --> <bean name="service" class="main.java.com.springaop.DomainObject"/> </beans>
二、需要代理的对象
这个对象必须是spring中注册的对象,也就是说必须是在spring配置文件中声明的对象
public class DomainObject {
private String name = "d" ;
public void show(){
System.out.println("name="+name);
}
}
三、AOP实现
这是最核心的,代理对象的触发方法,方法运行前运行后的通知都在这里实现:
@Component
@Aspect
public class ServiceAspect {
@Before("execution(* main.java.com.springaop.DomainObject.show(..))")
public void beforDo(JoinPoint joinPoint){
System.out.println("before");
}
@Around("execution(* main.java.com.springaop.DomainObject.show(..))")
public void around(JoinPoint joinPoint){
long start = System.currentTimeMillis();
try {
ProceedingJoinPoint jj = (ProceedingJoinPoint)joinPoint ;
jj.proceed();
long end = System.currentTimeMillis();
System.out.println("around " + joinPoint + "\tUse time : " + (end - start) + " ms!");
} catch (Throwable e) {
long end = System.currentTimeMillis();
System.out.println("around " + joinPoint + "\tUse time : " + (end - start) + " ms with exception : " + e.getMessage());
}
}
}
这里只实现了两个方面,
测试代码
public class AopTest {
public static void main(String[] args) {
ApplicationContext ap = new ClassPathXmlApplicationContext("main/java/conf/applicationContext.xml");
DomainObject obj = (DomainObject) ap.getBean("service");
obj.show();
}
}
如此简单,为何不用