新聞中心
AOP (Aspect Orient Programming),直譯過來就是 面向切面編程。AOP 是一種編程思想,是面向?qū)ο缶幊蹋∣OP)的一種補充。面向?qū)ο缶幊虒⒊绦虺橄蟪筛鱾€層次的對象,而面向切面編程是將程序抽象成各個切面。

創(chuàng)新互聯(lián)公司專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于網(wǎng)站設(shè)計、成都網(wǎng)站建設(shè)、龍口網(wǎng)絡(luò)推廣、成都小程序開發(fā)、龍口網(wǎng)絡(luò)營銷、龍口企業(yè)策劃、龍口品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務(wù),您的肯定,是我們最大的嘉獎;創(chuàng)新互聯(lián)公司為所有大學(xué)生創(chuàng)業(yè)者提供龍口建站搭建服務(wù),24小時服務(wù)熱線:18982081108,官方網(wǎng)址:www.cdcxhl.com
在Spring中AOP包含兩個概念,一是Spring官方基于JDK動態(tài)代理和CGLIB實現(xiàn)的Spring AOP;二是集成面向切面編程神器AspectJ。Spring AOP和AspectJ不是競爭關(guān)系,基于代理的框架的Spring AOP和成熟框架AspectJ都是有價值的,它們是互補的。
Spring無縫地將Spring AOP、IoC與AspectJ集成在一起,從而達(dá)到AOP的所有能力。Spring AOP默認(rèn)將標(biāo)準(zhǔn)JDK動態(tài)代理用于AOP代理,可以代理任何接口。但如果沒有面向接口編程,只有業(yè)務(wù)類,則使用CGLIB。當(dāng)然也可以全部強(qiáng)制使用CGLIB,只要設(shè)置proxy-target-class=”true”。
AOP中的術(shù)語
通知(Advice)
Spring切面可以應(yīng)用5種類型的通知:
前置通知(Before):在目標(biāo)方法被調(diào)用之前調(diào)用通知功能;
后置通知(After):在目標(biāo)方法完成之后調(diào)用通知,此時不會關(guān)心方法的輸出是什么;
返回通知(After-returning):在目標(biāo)方法成功執(zhí)行之后調(diào)用通知;
異常通知(After-throwing):在目標(biāo)方法拋出異常后調(diào)用通知;
環(huán)繞通知(Around):通知包裹了被通知的方法,在被通知的方法調(diào)用之前和調(diào)用之后執(zhí)行自定義的行為。
連接點(Join point)
切點(Poincut)
切面(Aspect)
引入(Introduction)
織入(Weaving)
這些術(shù)語的解釋,其他博文中很多,這里就不再贅述。
用2個例子來說明Spring AOP和AspectJ的用法
現(xiàn)在有這樣一個場景,頁面?zhèn)魅雲(yún)?shù)當(dāng)前頁page和每頁展示多少條數(shù)據(jù)rows,我們需要寫個攔截器將page、limit參數(shù)轉(zhuǎn)換成MySQL的分頁語句offset、rows。
先看Spring AOP實現(xiàn)
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);
}
}
2、定義后置處理器,將方法攔截件加入到advisor中。我們通過注解@Controller攔截所有的Controller,@RestController繼承于Controller,所以統(tǒng)一攔截了。
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());
}
}
3、萬事俱備只欠東風(fēng),Processor也寫好了,只需要讓Processor生效。
@Configuration
public class MethodInterceptorConfig {
@Bean
public RequestParamPostProcessor converter() {
return new RequestParamPostProcessor();
}
}`
這里有個坑需要注意一下,如果在配置類中注入業(yè)務(wù)Bean。
@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)
很多切面失效,如事務(wù)切面。這是因為注入了自定義的Bean,自定義的Bean優(yōu)先級最低,由最低優(yōu)先級的BeanPostProcessor來加載并完成初始化的。但為了加載其中的RequestParamPostProcessor,導(dǎo)致不得不優(yōu)先裝載低優(yōu)先級Bean,此時事務(wù)處理器的AOP等都還沒完成加載,注解事務(wù)初始化都失敗了。但Spring就提示了一個INFO級別的提示,然后剩下的Bean由最低優(yōu)先級的BeanPostProcessor正常處理。
AspectJ方式實現(xiàn)切面
@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的兩種不同用法,但達(dá)到的能力是一樣的。
Sping AOP在組織、抽象代碼場景中更加適合,AspectJ用于單純的切面來實現(xiàn)某項功能更加簡潔。
網(wǎng)頁標(biāo)題:詳解Spring中AOP
文章起源:http://www.5511xx.com/article/dhpsghj.html


咨詢
建站咨詢
