在idea中利用Spring進行面向切面程式設計(AOP)的一個例子
阿新 • • 發佈:2019-02-07
(1)在idea中新建立一個maven專案aopAspectj,,編寫POM檔案,匯入jar包:
(2)編寫一個介面:Performance(可以代表任何型別的現場表演)<dependencies> <!--aspectj依賴--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.10</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjtools</artifactId> <version>1.8.10</version> </dependency> <!--spring相關包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.1.RELEASE</version> </dependency> </dependencies>
public interface Performance {
public void perform();
}
(3)實現介面Performance方法。建立了一個歌舞劇表演
public class Theatre implements Performance{
public void perform(){
System.out.println("50個人正在表演舞臺劇");
}
}
(4)使用註解@Aspect來定義切面。在表演之前的動作有silenceCellPhones和takeSeats 。表演成功後的動作:applause。表演異常的動作有demandRefund
@Aspect //表明該類別是一個切面 public class Audience { @Pointcut("execution(** Performance.perform(..))") //定義命令的切點 public void performance(){} @Before("performance()") //在表演之前 public void silenceCellPhones(){ System.out.println("Silencing cell phones"); } @Before("performance()") //在表演之前 public void takeSeats(){ System.out.println("Taking seats"); } @AfterReturning("performance()") //表演之後 public void applause(){ System.out.println("CLAP CLAP CLAP!!!"); } @AfterThrowing("performance()") public void demandRefund(){ //表演失敗之後 System.out.println("Demanding a refund"); } }
其中@Pointcut是用來定義performance(),使它可以代表含義"execution(** Performance.perform(..))"
(5)然後建立配置類ConcertConfig,用來把Aspectj自啟動代理。其中@EnableAspectJAutoProxy來啟動Aspectj代理。
@Configuration
@EnableAspectJAutoProxy //啟用Aspectj自動代理
public class ConcertConfig {
@Bean //聲明瞭一個切面bean
public Audience audience(){
return new Audience();
}
@Bean
public Performance theatre(){
return new Theatre();
}
}
(6)測試主類PerformanceTest
ublic class PerformanceTest {
public static void main(String[] args){
//載入java配置類獲取Spring應用上下文
ApplicationContext ac=new AnnotationConfigApplicationContext(ConcertConfig.class);
//獲取播放器
Performance pf=ac.getBean(Performance.class);
//播放
pf.perform();
}
}
(7)結果顯示: