1. 程式人生 > >Spring基礎學習(四 AOP 註解實現)

Spring基礎學習(四 AOP 註解實現)

配置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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-4.1.xsd
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">

	<context:component-scan base-package="com.lanou.*"/>
	
	<!-- 開啟AOP註解 -->
	<aop:aspectj-autoproxy />

	
</beans>

BookImpl

@Component("bookDao")
public class BookImpl implements BookDao{

	@Override
	public void save() {
		System.out.println("從前有座山!");
		
	}

}

BookAspect

@Aspect
@Component
public class BookAspect {
		
	@Before("execution(* com.lanou.bookService.BookService.*(..))")
	public void logBefore() {
		System.out.println("日誌之前");
	}
	
	@After("execution(* com.lanou.bookService.BookService.*(..))")
	public void logBefore1() {
		System.out.println("日誌之前");
	}
    //環繞通知
		@Around("execution(* com.lanou.bookService.BookService.*(..))")
		public Object logAround(ProceedingJoinPoint point) {
//			Object[] objects = point.getArgs();
//			System.out.println(point.getSignature().getName());
//			System.out.println(point.getSignature().getDeclaringTypeName());
//			System.out.println(point.getSignature().getModifiers());
			//如果呼叫的的方法是saveBookinfo,而不是其它方法的話,我不呼叫
			System.out.println(point.getSignature().getName());
			if(point.getSignature().getName().equals("save")) {
				System.out.println("修改成功……");
				return null;
			}else {
				//繼續執行
				try {
					return point.proceed();
				} catch (Throwable e) {
					e.printStackTrace();
				}
			}
			
			return null;
		}
}