Spring AspectJAutoProxy切面初体验
Spring 强大之处在于配置和Aop,针对切面的编程大概是Spring如此长久的根本原因了吧,先来感受下Spring下 AspectJ的切面
eg:需求:在执行实现了接口Performance的对象的perform方法前后,加一些自定义的输出(实际运用中肯定会是一些业务逻辑,比如日志打印,监控,具体业务逻辑来实现低耦合的代码)
1.好了,首先我们把Performance接口和实现先创建好
1 package com.rocher.eventbus.annotation; 2 3 public interface Performance { 4 public void perform(); 5 }
实现:
1 package com.rocher.eventbus.annotation; 2 3 4 public class Performer implements Performance { 5 6 public void perform() { 7 System.out.println("表演开始"); 8 } 9 }
2.创建切面Audience
1 package com.rocher.eventbus.annotation; 2 import org.aspectj.lang.ProceedingJoinPoint; 3 import org.aspectj.lang.annotation.*; 4 5 @Aspect 6 public class Audience { 7 8 @Pointcut(value = "execution(* com.rocher.eventbus.annotation.Performance.perform(..))") 9 public void performance(){ 10 11 } 12 13 @Before("performance()") 14 public void silenceCellPhone(){ 15 System.out.println("关闭 Cell"); 16 } 17 18 @Before("performance()") 19 public void takeSeats(){ 20 System.out.println("坐下"); 21 } 22 23 @AfterReturning("performance()") 24 public void appLause(){ 25 System.out.println("CLAP CLAP"); 26 } 27 28 29 @AfterThrowing("performance()") 30 public void demandRefund(){ 31 System.out.println("Demand A Refund"); 32 } 33 34 @Around("performance()") 35 public void WatchPerformce(ProceedingJoinPoint proceedingJoinPoint){ 36 try{ 37 System.out.println("1111"); 38 proceedingJoinPoint.proceed(); 39 System.out.println("2222"); 40 }catch (Throwable throwable){ 41 System.out.println("Demand"); 42 } 43 } 44 }
3.我们把切面和Performance以bean的方式暴露出来
1 package com.rocher.eventbus.annotation; 2 3 import org.springframework.context.annotation.Bean; 4 import org.springframework.context.annotation.ComponentScan; 5 import org.springframework.context.annotation.Configuration; 6 import org.springframework.context.annotation.EnableAspectJAutoProxy; 7 8 @Configuration 9 @EnableAspectJAutoProxy 10 @ComponentScan 11 public class TrackCounterConfig { 12 @Bean 13 public Audience audience() 14 { 15 return new Audience(); 16 } 17 18 @Bean 19 public Performance performanceBean() { 20 return new Performer(); 21 22 } 23 }
这里的@EnableAspectJAutoProxy 表示启用AspectJ自动代理
4.最后我们在测试模块加入测试代码
1 package AspectJTest; 2 3 import com.rocher.eventbus.annotation.Performance; 4 import com.rocher.eventbus.annotation.TrackCounterConfig; 5 import org.junit.Test; 6 import org.junit.runner.RunWith; 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.test.context.ContextConfiguration; 9 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 10 11 @RunWith(SpringJUnit4ClassRunner.class) 12 @ContextConfiguration(classes = TrackCounterConfig.class) 13 public class Perform_Test { 14 @Autowired 15 private Performance performer; 16 17 @Test 18 public void Test1() { 19 performer.perform(); 20 } 21 22 }
最后输出:
1111
关闭 Cell
坐下
表演开始
2222
CLAP CLAP
浙公网安备 33010602011771号