當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring AOP编程-aspectJ注解开发
生活随笔
收集整理的這篇文章主要介紹了
Spring AOP编程-aspectJ注解开发
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1、編寫目標
public interface ICustomerService {public void save();public void search();public int update(); } @Service public class CustomerServiceImpl implements ICustomerService {@Overridepublic void save() {System.out.println("customerService save...");}@Overridepublic void search() {//System.out.println(10/0);System.out.println("customerService search...");}@Overridepublic int update() {System.out.println("customerService update...");return 10;}}在Spring配置文件applicationContext.xml中配置掃描注解。必須在spring的配置文件中開啟aspectJ注解自動代理功能。
<?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:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"><context:component-scan base-package="cn.nwtxxb" /><!-- 開啟aspectj注解自動代理 --><aop:aspectj-autoproxy proxy-target-class="true"/> </beans>2、編寫增強(advice)使用@Aspect來聲明切面,使用@Before來聲明前置通知
//通知 @Component @Aspect // 聲明當前的bean就是一個切面 public class CustomerServiceHelper {@Pointcut("execution(* *.s*(..))")private void mypointcut(){}@Pointcut("execution(* *.update(..))")private void mypointcut1(){}// 前置通知@Before("mypointcut()||mypointcut1()")public void before() {System.out.println("前置通知...");}// 后置通知@AfterReturning(value = "execution(* *.update(..))", returning = "value")public void afterReturning(JoinPoint jp, Object value) {System.out.println("后置通知,目標方法的返回是" + value);}// 環(huán)繞通知@Around("mypointcut()")public Object around(ProceedingJoinPoint pjp) throws Throwable {System.out.println("環(huán)繞前...");Object value = pjp.proceed();System.out.println("環(huán)繞后");return value;}// 異常拋出通知@AfterThrowing(value = "mypointcut()", throwing = "ex")public void afterThrowing(JoinPoint jp, Throwable ex) {System.out.println("異常拋出通知:" + ex);}// 最終通知@After("mypointcut()")public void after() {System.out.println("最終通知");} }4、測試
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext.xml") public class AspectAnnotationTest {@Autowiredprivate ICustomerService customerService;@Testpublic void test1() {customerService.update();}}總結
以上是生活随笔為你收集整理的Spring AOP编程-aspectJ注解开发的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring AOP编程-aspectJ
- 下一篇: Spring AOP编程-aspectJ