定義了一個切面
package com.javastudy.study;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class Audience {
@Pointcut("execution(public * com.javastudy.study.IPerformance.perform(..))")
public void performance() {}
@Before("performance()")
public void silenceCellPhone() {
System.out.println("Silence cell phones");
}
@Before("performance()")
public void takeSeats() {
System.out.println("Take seats");
}
@AfterReturning("performance()")
public void applause() {
System.out.println("CLAP CLAP CLAP");
}
@AfterThrowing("performance()")
public void demandRefund() {
System.out.println("Demanding a refund");
}
}
定義了切面的目標類
package com.javastudy.study;
import org.springframework.stereotype.Component;
@Component
public class SingPerformance implements IPerformance{
public void perform() {
System.out.println("i will sing a song.");
}
public static void main(String[] args) {
System.out.println("test perform.");
SingPerformance p = new SingPerformance();
p.perform();
}
}
在Controller中呼叫可以觸發切面,但是加了main函式,直接呼叫SingPerformance的perform函式不起作用
ackage com.javastudy.study;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/perform")
public class performanceController {
@Autowired
SingPerformance perform;
@GetMapping("/1")
public void perform1() {
perform.perform();
}
public static void main(String[] args) {
SingPerformance performance = new SingPerformance();;
performance.perform();
}
}
uj5u.com熱心網友回復:
你的意思是直接運行main方法切面不管用?uj5u.com熱心網友回復:
你直接new出來的物件,怎么能進的了切面呢?你如果要獨立單元測驗,可以用spring-junit進行測驗,否則你spring框架都沒啟動,根本沒有ioc和aop的概念。
你可以先了解一下aop的原理是什么?aop的原理是注入的是一個cglib代理的物件,而不是你的原生物件了,所以才能夠給你進入到切面里面。
uj5u.com熱心網友回復:
是的,打開瀏覽器訪問那個介面就有效果
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/225640.html
標籤:Web 開發
上一篇:Java求助
下一篇:論Python和Java?
