Table of contents
-
introduce
- Java is not a dynamic language; once a class is compiled, it is difficult to add new functionality to the class
- Aspects can add additional functionality to existing methods, why not add new methods to an object?
- In fact, aspects can add new methods to Spring beans using an AOP concept called introduction
-
analyze
- In Spring, aspects are just proxies that implement the same interface as the beans they wrap
- What if, in addition to implementing these interfaces, the proxy could also expose new interfaces?
- In that case, the bean notified by the aspect looks like it implements the new interface, even if the underlying implementation class does not implement these interfaces.
- The diagram shows how they work:
- Using Spring AOP, we can introduce new methods to beans
- The proxy intercepts the call and delegates to other objects that implement the method
- Note that when a method of the introduced interface is called, the proxy delegates the call to some other object that implements the new interface
- In fact, the implementation of a bean is split into multiple classes
- @DeclareParents annotation, which can add new behaviors (add new methods) to the proxy target class
- The @DeclareParents annotation consists of three parts:
- The value attribute specifies which type of bean should introduce the interface (the plus sign after the tag indicates all subtypes of the interface, not the interface itself)
- The defaultImpl attribute specifies the class that provides the implementation for the imported functionality
- The static property annotated by @DeclareParents indicates that the interface is to be introduced
-
example
- Proxied bean:
- Proxy Enhancement Class:
- Proxy class configuration:
- Enable AspectJ auto-proxying:
- Test class:
- The result is:
- Some people may ask why not add new methods directly to the original interface
- Of course, this is also possible, but there is a problem with this. If there are many implementation classes under the original interface, all implementation classes need to be modified.
- This can be done functionally, but it is not the best practice from a design point of view
- Moreover, sometimes there is no chance to modify all the implementation classes, for example, if the original class referenced is provided by a third party and there is no source code
- In this case there is no way to solve the problem by directly extending the original class