Wechat official account: Rhubarb Run follow me for more interesting interview questions.

1. At the beginning of AOP

For example, the following code gets the product information based solely on the product Id

public GoodsVo getGoodsVoByGoodsId(long goodsId) {
    return goodsMapper.getGoodsVoByGoodsId(goodsId);
}
Copy the code

It’s not uncommon for logs to be added before and after in order to observe execution.

public GoodsVo getGoodsVoByGoodsId(long goodsId) {
    Log.info("get Goods info, goodsId:" + goodsId);
    GoodsVo goodsVoByGoodsId = goodsMapper.getGoodsVoByGoodsId(goodsId);
    Log.info("get Goods info, goodInfos:" + goodsVoByGoodsId);
    return goodsVoByGoodsId;
}
Copy the code

Boy, the real business code is only one line, and the extra log is two lines. This is a simple requirement, but in production, with every iteration, the business code gets buried in “extra useless code” and the system becomes extremely difficult to maintain.

1. Why is AOP needed

In order to better solve this problem, predecessors put forward AOP (Aspect Oriented Programming), as a supplement of OOP (Object Oriented Programming).

Why is it called an Aspect? It is essentially an abstraction of logic, Aspect to AOP what Class is to OOP.

The Aspect meaning

AOP was introduced to solve the problem of OOP deficiencies, and is not a separate concept, all said to face the aspect, no aspect? How do you cut it?

2. AOP implementation

AOP is an idea, not a language. AOP needs to be implemented in a language, just as OOP implementations have Java, C++, etc

The most famous is AspectJ, which is essentially a Java version of ASpect.

A dynamic proxy

During runtime, the corresponding proxy object is dynamically generated for the corresponding interface.

Significant drawback: All classes that need to be woven need to implement interfaces

Dynamic bytecode enhancement

When building a bytecode file on the fly, weave in the corresponding logic, and be truly unaware

Disadvantages: Cannot be extended if the class you want to extend is final.

conclusion

This article briefly explained why YOU need AOP, but AOP is not unique to Java; it is an idea. When you know why you’re here, it’s easier to know what to do.

The next article introduces the core idea behind implementing AOP: the dynamic proxy pattern.