Indoor, Outdoor & Kids' Trampolines

AOP – 11 – The Basics of Spring Framework

Hello. In this session, we are going to
look at the part of Spring’s functionality that a bit goes beyond the scope of Core container. This is Aspect-Oriented Programming. As I mentioned before,
Spring implements support of AOP, and a lot of its utility classes and
functions work with help of this technology. In addition, Spring can work
with another popular AOP library – AspectJ. For the start, let’s figure out
what sort of technologies these are. AOP is a programming paradigm
that aims to increase modularity by allowing the separation
of cross-cutting concerns. Hmm… What does it mean? Roughly speaking, it means that
you can externalize the code, that is present in different classes, which are not connected with each other
in any way, into separate concerns. First of all, there’s not going
to be any code duplication, secondly, the classes will not know
anything about this common code concern. It is going to be executed in a magical way due to using AOP libraries in your program. So, what do these cross-cutting
concerns look like? If we analyze some common application, imagine there are some services that are
not connected with each other? Each service may consist of a few classes, the services may even call each other, but overall they are independent. Cross-cutting concerns, it may be logic connected with security, logging, monitoring etc. These concerns are not
necessarily used in some services but still have some different logic. But where do aspects come from? Let’s examine it with help of
the following example. Imagine that we have a program with three
different hierarchies of the classes. They are separate from each other in every way. The first one deals with, let’s say, databases,
the second one – with connection with the external system, the third one performs
some mathematical calculations. They are not connected with each other. And here comes a new requirement –
add activities monitoring into a couple of places of our program. We can, of course, write the call of
the necessary methods in all classes, but we’ll get duplication. So far that these places are located
within the classes of one hierarchy, we can avoid code duplication if we place the common logic in the superclass. By using Template pattern method
we can even put it in such a way that subclasses will not
know anything about it. Then there comes another requirement. Remove the existing monitoring for some time and implement a new one
in one class of each hierarchy. A problem comes up. Should we create one superclass for all of them? Not very good and sometimes just impossible. Duplicate the code? Doesn’t sound like a good idea As an option, create utility class with static methods. Then you’ll have to put
the call of methods everywhere and then you’ll have issues with testing. You may also want to inject
the necessary classes. Still, clever customers
can change the requirements. They’ll ask you to make it
the old way in one hierarchy and leave as it is in the other one. Here we have different logic of monitoring,
what’s more, it’s implemented in different classes, but it’s the same in some places. Finally, you may end up in a situation where in different classes you have a lot of code, which doesn’t influence the logic of the application,
a part of it is either disabled by the flags or commented out, the other part is duplicated. The aspect will help us to solve this problem. It’s a separate class,
in which we will place all the cross-cutting concerns. The aspects will be able to inherit each other, or we’ll be able to create a few
different ones based on their functions. The aspect will exist in such a way that the other classes of the
application won’t know anything about it as they will not call it. The aspect will connect the necessary logic
into the corresponding point of the program. And during execution that logic will be called. We will be able to connect
different logic into different points that are not connected with each other, but for which the presence of
aspect’s functionality is important. When changing the requirements, we’ll be able to remove the connection
between the aspect and the classes of the application. Just to remind you, there’s
no need to change the classes for this. What are AOP’s main notions? First and most importantly, it’s the Aspect. It’s a collection of cross-cutting concerns. It’s preferable to make the aspects
targeted at some specific task to separate duties between different classes. There’s always a pointcut inside the aspect. It defines where the aspect will be applied. ‘Where’ means in which class, in which method, probably, in all the methods of some interface, or methods marked with some annotation. Joint point indicates a specific place
in the class where the aspect is connected. That is, pointcut is a template
by which a few classes may function. There are going to be one or
more specific points (joint point), where the aspect will be executed. There’s also advice which
contains the code of the aspect that will be executed
in the places of connection. That is, it can be authorization,
collection of statistics, call of logging etc. Advice also specifies when
the code will be run – at the beginning of the method,
by completion etc. The possibilities that Spring’s
AOP implementation gives us are quite constrained but they are absolutely enough for solving the majority of
problems in enterprise applications. Spring AOP doesn’t require
usage of special class loaders or compilers and executes implementation
of cross-cutting functionality with help of proxy objects. So it works in such a way that
when Spring creates the context and sees that some bean needs aspect to be applied, it creates the proxy for it and
returns it instead of the object. When you will be addressing the bean,
the proxy method will be called, that will probably execute advice at some moment and will redirect the call
directly to the object of the bean. Because proxy is used, Spring supports
only one type of joint point – the method execution over beans in the context. And very often, it’s enough. If you still need to use more fancy methods, such as interception of setting
the field values of the class, static initialization of the class or you just want to apply the aspects for the classes that are not declared as beans –
then you have to use an external library such as AspectJ. Spring is not trying to compete
with other implementations of AOP. It offers flexible possibilities of using AOP in close collaboration with IoC container,
even if you use AspectJ. On balance, if you don’t need such
a wide range of functionality, you can easily start with the basics and move on to the profundities. Let’s have a look at how it’s possible
to use pointcut in the application. You write an appropriate designator, after which you specify in the brackets the parameters or the signature of the method
that is assigned as a pattern. So, which designators does Spring support? The most important one is ‘execution’. It allows to match the execution of the method in the bean. ‘Within’ allows to choose
the joint point in some specific classes, that is you will connect
to the methods not of any class, but of some specific ones. ‘Target’ limits the type of the object,
in which the method is called. ‘This’ specifies the type of the
current object or the bean, for which the method is called. In Spring AOP case, this will specify the proxy, while target will specify the proxy object. ‘Args’ allows to specify the classes of method’s parameters. @target, @within allow to implement the same constraints, but the annotations of the classes
will be checked at the same time. AspectJ library also contains
lot of additional pointcut designators that allow to connect
to the constructors of the objects, exception processors,
static initializations. As I mentioned before,
Spring AOP doesn’t support them. ou can read about the PointCut
references in more detail Yin the documentation to AspectJ library. When using Spring AOP,
you will mostly use pointcut execution. If you use the signature of the methods,
you can use an asterisk to define the patterns and colon
to define any arguments of the methods. In this slide you can see the examples
of using different pointcuts. Before we finish, let’s have a look
what ‘Advice’ there are in AOP. It’s elementary. The code of the aspect
can be executed before joint-point, that is in the case of Spring
it will be before the method of the bean. This execution can be performed
after the method, regardless what it returned. After the regular finish of the method or if it throws an exception. It’s also possible to execute
advice instead of the method. Around advice allows to enter the method if needed. OK, I understand that theory
is a very exciting thing, but practice makes perfect,
thus let’s create a couple of aspects. So, don’t hesitate to start
the next session! I’ll be waiting for you there.

Reader Comments

  1. спасибо за качественный контент! на спринге со 2-ой версии все и так знал, но хотелось причесать знания. Узнал новое, что не использовал. Буду пробовать.

  2. на Вашем ютуб-канале есть видео про горячие клавиши в intellij Idea?

    Вообще в ютубе есть видео на эту тему, но там используют не больше 40% всех горячих клавиш.

Leave a Reply

Your email address will not be published. Required fields are marked *