掃二維碼與項目經理溝通
我們在微信上24小時期待你的聲音
解答本文疑問/技術咨詢/運營咨詢/技術建議/互聯(lián)網交流
AOP (Aspect Orient Programming),直譯過來就是 面向切面編程。AOP 是一種編程思想,是面向對象編程(OOP)的一種補充。面向對象編程將程序抽象成各個層次的對象,而面向切面編程是將程序抽象成各個切面。

創(chuàng)新互聯(lián)公司專注為客戶提供全方位的互聯(lián)網綜合服務,包含不限于網站設計、成都網站建設、龍口網絡推廣、成都小程序開發(fā)、龍口網絡營銷、龍口企業(yè)策劃、龍口品牌公關、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務,您的肯定,是我們最大的嘉獎;創(chuàng)新互聯(lián)公司為所有大學生創(chuàng)業(yè)者提供龍口建站搭建服務,24小時服務熱線:18982081108,官方網址:www.cdcxhl.com
在Spring中AOP包含兩個概念,一是Spring官方基于JDK動態(tài)代理和CGLIB實現(xiàn)的Spring AOP;二是集成面向切面編程神器AspectJ。Spring AOP和AspectJ不是競爭關系,基于代理的框架的Spring AOP和成熟框架AspectJ都是有價值的,它們是互補的。
Spring無縫地將Spring AOP、IoC與AspectJ集成在一起,從而達到AOP的所有能力。Spring AOP默認將標準JDK動態(tài)代理用于AOP代理,可以代理任何接口。但如果沒有面向接口編程,只有業(yè)務類,則使用CGLIB。當然也可以全部強制使用CGLIB,只要設置proxy-target-class=”true”。
AOP中的術語
通知(Advice)
Spring切面可以應用5種類型的通知:
前置通知(Before):在目標方法被調用之前調用通知功能;
后置通知(After):在目標方法完成之后調用通知,此時不會關心方法的輸出是什么;
返回通知(After-returning):在目標方法成功執(zhí)行之后調用通知;
異常通知(After-throwing):在目標方法拋出異常后調用通知;
環(huán)繞通知(Around):通知包裹了被通知的方法,在被通知的方法調用之前和調用之后執(zhí)行自定義的行為。
連接點(Join point)
切點(Poincut)
切面(Aspect)
引入(Introduction)
織入(Weaving)
這些術語的解釋,其他博文中很多,這里就不再贅述。
現(xiàn)在有這樣一個場景,頁面?zhèn)魅雲?shù)當前頁page和每頁展示多少條數(shù)據(jù)rows,我們需要寫個攔截器將page、limit參數(shù)轉換成MySQL的分頁語句offset、rows。
1、實現(xiàn)MethodInterceptor,攔截方法
public class MethodParamInterceptor implements MethodInterceptor {
@Override
@SuppressWarnings("unchecked")
public Object invoke(MethodInvocation invocation) throws Throwable {
Object[] params = invocation.getArguments();
if (ArrayUtils.isEmpty(params)) {
return invocation.proceed();
}
for (Object param : params) {
//如果參數(shù)類型是Map
if (param instanceof Map) {
Map paramMap = (Map) param;
processPage(paramMap);
break;
}
}
return invocation.proceed();
}
/**
*
* @param paramMap
*/
private void processPage(Map paramMap) {
if (!paramMap.containsKey("page") && !paramMap.containsKey("limit")) {
return;
}
int page = 1;
int rows = 10;
for (Map.Entry entry : paramMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
if ("page".equals(key)) {
page = NumberUtils.toInt(value, page);
} else if ("limit".equals(key)) {
rows = NumberUtils.toInt(value, rows);
}else {
//TODO
}
}
int offset = (page - 1) * rows;
paramMap.put("offset", offset);
paramMap.put("rows", rows);
}
}
public class RequestParamPostProcessor extends AbstractBeanFactoryAwareAdvisingPostProcessor
implements InitializingBean {
private Class validatedAnnotationType = Controller.class;
@Override
public void afterPropertiesSet() throws Exception {
Pointcut pointcut = new AnnotationMatchingPointcut(this.validatedAnnotationType, true);
this.advisor = new DefaultPointcutAdvisor(pointcut, new MethodParamInterceptor());
}
}
@Configuration
public class MethodInterceptorConfig {
@Bean
public RequestParamPostProcessor converter() {
return new RequestParamPostProcessor();
}
}`
@Configuration
public class MethodInterceptorConfig {
@Autowired
private UserService userService;
@Bean
public RequestParamPostProcessor converter() {
return new RequestParamPostProcessor();
}
}
啟動時,會出現(xiàn):
2019-11-08 14:55:50.954 INFO 51396 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'sqlSessionFactory' of type [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-11-08 14:55:50.960 INFO 51396 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'sqlSessionTemplate' of type [org.mybatis.spring.SqlSessionTemplate] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-11-08 14:55:51.109 INFO 51396 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'rememberMapper' of type [com.sun.proxy.$Proxy84] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-11-08 14:55:53.406 INFO 51396 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
很多切面失效,如事務切面。這是因為注入了自定義的Bean,自定義的Bean優(yōu)先級最低,由最低優(yōu)先級的BeanPostProcessor來加載并完成初始化的。但為了加載其中的RequestParamPostProcessor,導致不得不優(yōu)先裝載低優(yōu)先級Bean,此時事務處理器的AOP等都還沒完成加載,注解事務初始化都失敗了。但Spring就提示了一個INFO級別的提示,然后剩下的Bean由最低優(yōu)先級的BeanPostProcessor正常處理。
@Component@Aspect@Slf4jpublic class MethodParamInterceptor {
@Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
public void paramAspect() {
}
@Before("paramAspect()")
public void beforeDataSource(JoinPoint joinPoint) {
Arrays.stream(joinPoint.getArgs()).forEach(paramObject -> {
if (paramObject instanceof Map) {
Map parameter = (Map) paramObject;
processPage(parameter);
}
});
}
private void processPage(Map
paramMap) {
if (null == paramMap) {
ret }
if (!paramMap.containsKey(
"page") && !paramMap.containsKey(
"limit")) {
return; } int page = 1; int rows = 10;
for (Map.Entry
entry : paramMap.entrySet()) { String key = entry.getKey(); String value = entry.getValue().toString();
if (
"page".equals(key)) { page = NumberUtils.toInt(value, page); }
else
if (
"limit".equals(key)) { rows = NumberUtils.toInt(value, rows); } } int offset = (page - 1) * rows; paramMap.put(
"offset", offset); paramMap.put(
"rows", rows); } @After(
"paramAspect()") public void afterDataSource(JoinPoint joinPoint) { } }
從上面兩個例子可以對比出SpringAOP和AspectJ的兩種不同用法,但達到的能力是一樣的。
Sping AOP在組織、抽象代碼場景中更加適合,AspectJ用于單純的切面來實現(xiàn)某項功能更加簡潔。

我們在微信上24小時期待你的聲音
解答本文疑問/技術咨詢/運營咨詢/技術建議/互聯(lián)網交流