利用aop的方式打印日志仑氛。
蠻好用的草姻。
廢話不多說瀑构,直接上代碼笨腥。
1 Log注解定義
//Log.java
package com.sigh.test;
import java.lang.annotation.*;
/**
* Created by sigh on 2015/6/25.
*/
/**
* 攔截器定義
* @see LogAspect
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD})
public @interface Log {
}
2 攔截器定義
//LogAspect.java
package com.sigh.test;
import net.paoding.rose.scanning.context.RoseAppContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
/**
* Created by sigh on 2015/6/25.
*/
@Service
@Aspect
public class LogAspect {
private static final Logger LOGGER = LoggerFactory.getLogger(LogAspect.class);
@Pointcut("@annotation(Log)")
public void logPointcut() {
}
@Around("logPointcut()")
public Object doSurround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
Object[] objects = proceedingJoinPoint.getArgs();
String name = proceedingJoinPoint.getSignature().getName();
long startTime = System.currentTimeMillis();
Object result = proceedingJoinPoint.proceed();
LOGGER.info("class: {}, function name: {}", proceedingJoinPoint.getTarget().getClass().getName(), name);
LOGGER.info("in args: <{}>, out args: <{}>", objects, result);
LOGGER.info("execute time: {}", System.currentTimeMillis() - startTime);
return result;
}
public static void main(String[] args) {
//ApplicationContext applicationContext = new FileSystemXmlApplicationContext("src/spring-config.xml");
ApplicationContext applicationContext = new RoseAppContext().getApplicationContext();
First first = (First) applicationContext.getBean("first");
Second second = (Second) applicationContext.getBean("second");
Third third = (Third) applicationContext.getBean("third");
first.run(3);
first.report();
second.doWork(1, 2, true);
second.display();
//third.logTest(new Object[] {first, second});
third.logTest(null);
}
}
3 示例測試類
//First.java
package com.sigh.test;
import org.springframework.stereotype.Service;
/**
* Created by sigh on 2015/6/9.
*/
@Service
public class First {
@Log
public boolean run(int x) {
System.out.println("first " + x);
return true;
}
@Log
public void report() {
System.out.println("report first");
}
}
//Second.java
package com.sigh.test;
import org.springframework.stereotype.Service;
/**
* Created by sigh on 2015/6/9.
*/
@Service
public class Second {
@Log
public long doWork(int a, long b, boolean c) {
System.out.println("second " + a + " " + b + " " + c);
return 3;
}
@Log
public void display() {
System.out.println("display second");
}
}
//Third.java
package com.sigh.test;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* Created by sigh on 2015/6/26.
*/
@Service
public class Third {
@Log
public List<Object> logTest(Object[] objects) {
List<Object> list = new ArrayList<Object>();
for (Object o : objects) {
list.add(o);
}
return list;
}
}
4 applicationContext.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.sigh.test">
</context:component-scan>
<aop:aspectj-autoproxy proxy-target-class="true" />
</beans>
**<aop:aspectj-autoproxy proxy-target-class="true" /> **
這行很重要目尖,沒有的話無法攔截馒吴,具體是jdk代理和cglib代理的區(qū)別問題,如下:
(1) jdk代理實現(xiàn)的具體過程:
a. 獲取指定類上的所有接口列表
b. 確定要生成的代理類的類名瑟曲,默認(rèn)為com.sun.proxy.$ProxyXXXX
c. 根據(jù)需要實現(xiàn)的接口信息募书,在代碼中動態(tài)創(chuàng)建該P(yáng)roxy類的字節(jié)碼
d. 將對應(yīng)的字節(jié)碼轉(zhuǎn)換為相應(yīng)的class對象
e. 創(chuàng)建InvocationHandler實例handler,用來處理Proxy所有方法調(diào)用
f. Proxy的class對象以創(chuàng)建的handler對象為參數(shù)测蹲,實例化一個Proxy對象
(2) cglib代理的具體過程:
a. 查找指定類上的所有非final的public類型的方法定義
b. 將這些方法的定義轉(zhuǎn)換為字節(jié)碼
c. 將組成的字節(jié)碼轉(zhuǎn)換成相應(yīng)的代理的class對象
d. 實現(xiàn)MethodIntereceptor接口莹捡,用來處理對代理類上所有方法的請求
(3) 兩者的區(qū)別:
a. jdk使用接口+組合的方式實現(xiàn),而cglib使用繼承的方式實現(xiàn)扣甲,因此對于沒有接口的類來說篮赢,jdk代理不可用
b. 通常來說,jdk代理的所有功能cglib都具有琉挖,反之不然
基于以上原理启泣,可以解釋上述問題。
a. 當(dāng)沒有增加<aop:aspectj-autoproxy proxy-target-class="true" />時示辈,aop不生效——因為aop默認(rèn)使用jdk代理實現(xiàn)寥茫,而被攔截的類不具有接口。因此需要使用cglib代理
b. 當(dāng)方法非public時矾麻,aop不生效——因為cglib代理只代理非final的public類型方法
ps: 1. mvn配置起來很惡心纱耻,還有包的沖突問題
ps: 2. 如果不把目標(biāo)方法設(shè)置為public芭梯,使用注解攔截會有問題,調(diào)了半個下午