CustomerService
@Service
public class CustomerServiceImpl implements CustomerService {
@Override
public int add() {
// TODO Auto-generated method stub
System.out.println("add...");
return 10;
}
@Override
public void delete() {
// TODO Auto-generated method stub
System.out.println("delete...");
}
@Override
public void update() {
// TODO Auto-generated method stub
System.out.println("update...");
}
@Override
public void search() {
// TODO Auto-generated method stub
System.out.println("search...");
}
}
CustomerServiceHelper增强类
@Component
@Aspect //声明当前的bean是一个切面
public class CustomerServiceHelp {
//把切点抽取出来,下面的通知中引用切点
@Pointcut("execution(* *.add(..))")
private void myPointCut1(){}
@Pointcut("execution(* *.update(..))")
private void myPointCut2(){}
@Before("myPointCut1()||myPointCut2()")
public void before() {
System.out.println("前置通知...");
}
@AfterReturning(value="myPointCut1()",returning="value")
public void afterReturn(JoinPoint jp,Object value) {
System.out.println("后置通知,目标方法返回的是..."+value);
}
@Around("myPointCut1()")
public Object around(ProceedingJoinPoint proceed) throws Throwable {
System.out.println("环绕前...");
Object value = proceed.proceed();
System.out.println("环绕后...");
return value;
}
@AfterThrowing(value="myPointCut1()",throwing="ex")
public void afterThrow(JoinPoint jp,Throwable ex) {
System.out.println("发现异常..."+ex);
}
@After("myPointCut1()")
public void after() {
System.out.println("最终通知...");
}
}
Test
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class CustomerTest {
@Autowired
private CustomerService customerService;
@Test
public void test1() {
customerService.add();
}
}
结果:
环绕前...
前置通知...
add...
环绕后...
最终通知...
后置通知,目标方法返回的是...10
1.注意:
必须在spring的配置文件中开启aspectJ注解自动代理功能。
2.关于代理方式选择:
Proxy-target-class默认值是false,代表的是如果目标是有接口的使用proxy代理,如果没有接口使用cglib.
如果将proxy-target-class=true,不管目标是否有接口,都会使用cglib进行代理。
applicationContext.xml
<context:component-scan base-package="brooker.aopAnnotation"></context:component-scan>
<!-- 开启aspectj注解自动代理 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>