Intellij IDEA建立Spring專案之基於Aspectj的AOP操作(註解方式)
阿新 • • 發佈:2019-01-07
前言:
- 本文采用註解的方式進行Spring中基於Aspectj的AOP操作。
- 且此文是在已經瞭解了Spring中基於Aspectj的AOP操作原理的基礎上,再利用IDEA建立專案
- 本文采用建立專案的形式講解,並非講AOP原理
環境:
- Intellij IDEA 2017 CI
具體步驟
1、建立專案
建立專案如圖:
Book類:
package demo.spring.aop;
public class Book {
public void add(){
System.out.println("Book-add()........");
}
}
MyBook類:
package demo.spring.aop;
public class MyBook {
}
applicationContext.xml配置檔案:
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
TestAop類:
package demo.spring.aop;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestAop {
@Test
public void test(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Book book = (Book) applicationContext.getBean("book");
book.add();
}
}
2、配置applicationContext.xml配置檔案
applicationContext.xml配置檔案:
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--註解方式-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!--建立物件-->
<bean id="book" class="demo.spring.aop.Book"></bean>
<bean id="myBook" class="demo.spring.aop.MyBook"></bean>
</beans>
3、配置切面
MyBook類:
package demo.spring.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class MyBook {
//前置增強
@Before(value = "execution(* demo.spring.aop.Book.*(..))")
public void before(){
System.out.println("前置增強........");
}
//後置增強
@AfterReturning(value = "execution(* demo.spring.aop.Book.*(..))")
public void after(){
System.out.println("後置增強........");
}
//環繞增強
@Around(value = "execution(* demo.spring.aop.Book.*(..))")
public void arround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
//方法之前執行的程式碼
System.out.println("環繞增強 方法之前執行........");
//執行被增強的方法
proceedingJoinPoint.proceed();
//方法之後執行的程式碼
System.out.println("環繞增強 方法之後執行........");
}
}
4、測試
測試成功