0
我是Spring AOP和註解的新手。我試圖編寫一個使用Aspect的簡單程序。我無法弄清楚我出錯的地方。它不打印我在我的方面有什麼。Spring AOP - 無法執行方面
package com.business.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@EnableAspectJAutoProxy
@Configuration
public class PrintMain {
public static void main(String[] args) {
// Do I always need to have this. Can't I just use @Autowired to get beans
ApplicationContext ctx = new AnnotationConfigApplicationContext(PrintMain.class);
CheckService ck = (CheckService)ctx.getBean("service");
ck.print();
}
@Bean(name="service")
public CheckService service(){
return new CheckService();
}
}
package com.business.main;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class SimpleAspect {
@Around("execution(* com.business.main.CheckService.*(..))")
public void applyAdvice(){
System.out.println("Aspect executed");
}
}
package com.business.main;
import org.springframework.stereotype.Component;
@Component
public class CheckService{
public void print(){
System.out.println("Executed service method");
}
}
輸出:執行的服務方法
我希望打印的內容我在我的看點
我不得不做出兩處修改,使其工作1)實現接口2)添加@ ComponentScan。但我想知道爲什麼它沒有接口就無法工作......我讀了一些與CGLIB相關的內容,這些內容不能通過註釋強制執行。其次,爲什麼它沒有@ ComponentScan – karthik
@karthik因爲你只需要使用組件的工作,但春天不是把它作爲豆,指的ApplicationContext不會有它。當ApplicationContext連線時,它需要知道誰將連接成一個bean。 ApplicationContext不知道你是否需要Component或者你使用它,所以你需要使用Xml或ComponentScan來告訴Spring我需要連接一些bean。 – JonahCui
@karthik我的英語不太好。請原諒我。 – JonahCui