step1:定义主方法:
package com.how2java.service;
public class ProductService {
public void doSomeService(){
System.out.println("doSomeService");
}
}
step2:定义辅助功能:
package com.how2java.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
public class LoggerAspect {
public Object log(ProceedingJoinPoint joinPoint) throws Throwable { //通过环绕连接点获得被通知方法的参数;
System.out.println("start log:" + joinPoint.getSignature().getName());//通过getSignature返回被通知方法标识;
Object object = joinPoint.proceed();
System.out.println("end log:" + joinPoint.getSignature().getName());
return object;
}
}
step3:配置文件设置:
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean name="c" class="com.how2java.pojo.Category">
<property name="name" value="yyy" />
</bean>
<bean name="p" class="com.how2java.pojo.Product">
<property name="name" value="product1" />
<property name="category" ref="c" />
</bean>
<bean name="s" class="com.how2java.service.ProductService"> //配置主业务:"s": ProductService;
</bean>
<bean id="loggerAspect" class="com.how2java.aspect.LoggerAspect"/> //配置辅助功能:唯一id:"loggerAspect";
<aop:config>
<aop:pointcut id="loggerCutpoint".
expression=
"execution(* com.how2java.service.ProductService.*(..)) "/>
<aop:aspect id="logAspect" ref="loggerAspect">
<aop:around pointcut-ref="loggerCutpoint" method="log"/>//point-ref:切点位置;method:辅助用的方法;
</aop:aspect>
</aop:config>
</beans>
step4:注解实现AOP:
1.使用@Component("s") 注解ProductService 类:
@Component("s")
public class ProductService {
2.配置切面方法:
@Aspect 注解表示这是一个切面
@Component 表示这是一个bean,由Spring进行管理
@Around(value = "execution(* com.how2java.service.ProductService.*(..))") 表示对com.how2java.service.ProductService 这个类中的所有方法进行环绕的切面操作
@Aspect //声明辅助方法;
@Component //声明bean;
public class LoggerAspect {
@Around(value = "execution(* com.how2java.service.ProductService.*(..))") //声明使用的方法;Aroud:环绕切面;execution:切入点;
public Object log(ProceedingJoinPoint joinPoint) throws Throwable
3.修改配置文件:
<context:component-scan base-package="com.how2java.aspect"/> //扫描获得切面方法;
<context:component-scan base-package="com.how2java.service"/> //扫描获得主方法;
<aop:aspectj-autoproxy/> //开始切面操作;