Spring Framework - Lesson 4 - Aspect Oriented Programming - AOP
Vložit
- čas přidán 23. 05. 2019
- In Lesson #4 of the Spring stream we will find out what is AOP, and why is it important for Spring Framework. Did you miss the first lessons? You can still see them recorded!
01:46 Inversion of control
08:14 Creating the project
11:04 Main package & class
11:33 Configuration package
12:34 Service package
16:35 What is an aspect
17:41 Aspects package
22:10 Purpose of aspects
22:41 @Before join point
29:24 @After join point
30:34 @AfterReturning join point
31:42 @AfterThrowing join point
36:56 @Around join point
50:00 "proceed" method for a join point
Also. Don't forget to ask questions, leave feedback, subscribe and follow me also on Twitter and LinkedIn !
Code on GitHub:
github.com/lspil/youtubechann...
#spring #framework #aspects #orientedprogramming #java #springframework #lauretiuspilca - Věda a technologie
Liked it even before watching the video and also sharing with friends. You videos are great resource. Thank you!
Thank you for these videos!
Thank you, really good hands on tutorial
Useful and nicely explained! 😊 thank you!
Very useful,
I hope you explain the concept of the annotations in Java, in the future, because they are most used by spring.
Thank you.
Great Video! Thank you!
super tare canalul 🤩
you are the best ❤
Thank you :)
thank u
Amazing content! You are one of the best teachers I've ever met in my life. I understand everything clearly. Could you record tutorials for vaadin framework? As I see it is used very much in practice right now and your explanations would help me a lot. Thank you for your outstanding content!
Yes. I could try that. It's some years since I've last used Vaadin but I still remember the most important facts I guess :)
Thank you very much for your answer and I am looking forward to watching your videos about vaadin
great
Can you please add a video.. describing aop concepts like joint points, point cuts, advice in general. I feel the usage of these terms without describing them first a little confusing.
Hi Brajesh. Sure, I should have done that indeed. I see I have some gaps here. Thanks for the feedback.
Code on GitHub: github.com/lspil/youtubechannel/tree/master/springfundamentalse4
Amazing video thank you so much. Mr. Spilca I can't figure out what is the difference between spring-aop and spring-aspects packages? what is the logic in each of them?
Hi Hamed. To be honest with you I never asked myself this question by now. I will have to research what is in each. Sorry, for the moment I don't have an answer.
Hi Laurentiu. I have some questions related to the endpoints here. If I have an @After and an @AfterReturning or @AfterThrowing which one executes first?
I was thinking to myself that the @After would because it's a guaranteed method and I've see on a forum that this is correct but I tried your examples and everytime my @After method executes last.
Everytime "B" is printed the last.
Hi Cristian. That's an excellent question. Believe it or not, I don't think I've tried this so far. I would say that one shouldn't rely on the order of the events as a best practice. I will try it myself and debug a little on it to understand how it's implemented behind the scenes in Spring.
Hi Cristian, I saw this comment of yours and I think I can answer this question:
The @After advice always executes last because it corresponds to the java "finally".
Imagine that you have defined a method named "interceptedMethod". I believe the execution of the method roughly works this way:
try {
interceptedMethod();
afterReturning();
} catch (e) {
afterThrowing();
}
finally {
after();
}
The finally statement always occurs last, and doesn't care whether an exception was thrown or not, as such, the @After advice always executes after the @AfterReturning and @AfterThrowing, wheter or not an exception was thrown.
I hope this can be useful to the people running into this question in the comment, and sorry for the poor explanation, my knowledge is not particularly deep.
Is @Around annotation used to implement Man-in-the_middle attack? If not, can it be used? Thanks!
Hi Muhammad. Spring aspects and man-in-the-middle have nothing in common. So the answer is no. Cheers!
Hey! It's a question to previous video "Spring Framework - Lesson 3", asking it here because somehow I can't comment there, it says that commenting is disabled.
Back to the question, you showed us how to create a simple app that connects to a database, adds products there, and lists them out. Is what you showed still relevant today, it's been 2 years since that video and I'm not sure if much has changed. Is it still the preferred way to create programs like this or do we use something else nowadays? I won't hide, my goal for now is to create a simple CRUD app to test my abilities and challenge myself, but I found other guides and they never write the code like you do. I haven't watched all of your lessons yet, right now I'm at lesson 4 (here :)), do you by any chance mention that topic later, writing CRUD app?
I'd like to thank you for the free lessons, they are a true life-saver for a beginner like me. I've tried other channels before, but you are the only one that makes it easy to understand, loving that you also describe your code and don't assume that we know everything :) Really happy that such a knowledgeable person is sharing those videos for free :)
Cheers, keep doing great work.
PS. If there's something hard to understand in my post, please let me know. I will clarify that
Hey. Yes. Almost everything you find on this channel is still relevant today. The Spring playlist especially. There are some things that changed a bit in the Spring Security playlist. Everything else is still hot and juicy.
Thanks :) Laur!. You stated at 22:58 that the @Before annotation is a Join point. Isn't that Advice?
Hi. Very good observation. I made a mistake.
@After and @AfterReturning raise this question in my mind. Who executed first return keyword or closing curly bracket “}” ?
I never thought about closing curly bracket as an instruction. I see {} more as a way to define the code block.
Is using AOP a good way to audit log & save state of a transaction in the database. E.g. if a payment Failed, we use AOP to save FAILED state in database & similarly for SUCCESS?
Hey. Yes. Of course everything depends on the case, but using AOP to decouple logging could be a good case.
have you already passed the spring certification?if yes, how much is it dificult?
I have actually passed all the Java EE certifications from Oracle. I am in progress still with the Spring certification but I am almost ready with all the specifications and I am working with Spring for 5 to 6 years already :)
Awesome video Laur Splica, this is awesome. I did not get clear from minute 53:40 onwards, when Laur talks about "being careful with the annotations since their retaintion time is around runtime" if anyone can clarify, that would be great thanks
Hi. Sure. I could clarify it. But I'm not sure I understand your question. What exactly about the annotations and the retention type makes confusion?
Is AOP a type of Decorator Pattern?
Hi Sansaz. Thanks for the question. Yes. I think you can think about AOP as a decorator.
@@laurspilca Thank you!
Thanks :) as always. Can you simply elaborate the following definitions because In this video you mainly focus on the implementation and not the theory. So I was interested in knowing these terms:
1. Aspect
2. Join point
3. Advice
3. Point cut
Hi. Sure. Here they are:
1. Aspect - piece of logic completely decoupled that executes when a specific point cut is triggered.
2. Join point - Action that triggers the execution of an aspect. For example the call of a method.
3. Pointcut - Expression that matches one or multiple join points.
4. Advice - When exactly relative to the join point will the aspect execute? Before, after?
I hope this clarifies your concerns.
@@laurspilca Thanks :)
if i try with autowiring the helloservice then getting exception
can somebody help?
Hi Pola. Maybe, but you need to tell us more details. For example, what exception do you get.
Hello!
Great lesson, thank you for all the explanation. Do you think that you can help us with the moment when the Class that we intercept calls internal methods, I understand that the call remains in the bean and it doesn't go through the advice again :)
Thank you!
Hi Cristina. Yes. You are right. That is because any internal call happens directly through instance "this". Instance "this" will always be of the type itself and cannot be augmented by Spring. That's why, any Spring capabilities (including custom aspects) won't be called for internal calls inside the same class.
@@laurspilca I saw that there are some solution (ex: using an injection of the class in it's own body, or using non-spring-orientated AOP framework - such as AspectJ). Do you have any recommendation? I'm currently trying to use it for logging some old projects :)
@@SaraCristina-ci2yq Yes, there are some "workarounds". For example, if you inject the object in its own class and use the injected field it will work since Spring will cover the object with an aspect. However, I don;t recommend you do that. It will complicate your code and make your app less maintainable. With time, it will add more and more technical debt.
hey Laur, I am facing a problem Im using generic entities so when i am intercepting with Aop i can not decorate or wrap it in a response it gives ClassCastException. how to solve this have you any idea ?
Hi. I need more details. What do you mean by generic entities? How do you aspect them?
@@laurspilca i am building a web app so i created generic interfaces for entities ,repo, service and controller . it was working well but now i wanted to intercept the controller for customized response like success,status, message and data by making a class with builder annotation so i used Aop as you instructed but now the problem im facing is that in Around method of aop only thing is returning is joinpoint.proceed() .. i cannot return any thing else ... if i do it says can not cast to Generic Entity .
????
Why we add spring-aspect and apo both in pom.xml. We only use spring aop
True fact. I'm not sure why I added both dependencies in this example. Probably just a fault of mine :)
@@laurspilca Ok
@@laurspilca isn't spring-aspect required for AspectJ annotations ?
@@harshbiyani3048 Hi Harsh. I think the spring-aspect annotation might also include that. Again, this is kind of a not really relevant detail thing to remember because dependencies and especially starter dependencies when it comes to Spring Boot tend to change often. So I don't usually keep track of all.
You didn't cover the arguments and returning
Hi. Good point. I'll make a separate video and detail more on this aspect. Thanks :)
Playback speed 2 is normal
Hi,
at 31:28 you see the output at console for @After and @AfterReturning pointcuts. From your output I get the sense that the output of @After is shown before the output the @AfterReturning. However, when I experiment with it, I find it reversed. Following my code:
@Aspect
@Component
public class HelloServiceAspect {
private static final Logger LOGGER = LoggerFactory.getLogger(HelloServiceAspect.class);
@Before("execution(* services.HelloService.hello(..))")
public void beforeHello() {
LOGGER.info("Just before calling `HelloService.hello()` method.");
}
@After("execution(* services.HelloService.hello(..))")
public void afterHello() {
LOGGER.info("Just after calling `HelloService.hello()` method.");
}
@AfterReturning(value = "execution(* services.HelloService.hello(..))", returning = "returnedValue")
public void afterHelloReturned(final String returnedValue) {
LOGGER.info("Hello method return: " + returnedValue);
}
}
Following my console output:
[INFO ] 2022-12-22 05:31:52.365 [main] HelloServiceAspect - Just before calling `HelloService.hello()` method.
[INFO ] 2022-12-22 05:31:52.371 [main] HelloServiceAspect - Hello method return: Hello Max
[INFO ] 2022-12-22 05:31:52.371 [main] HelloServiceAspect - Just after calling `HelloService.hello()` method.
**Question**: How is the order of execution defined when a join point has multiple advices (aspects) applied to it?
Thanks in advance.
Not OP but I think @AfterReturning is executed right after the hello() method returns a value (in this case "Max"). @After is executed after the hello() method has concluded, i.e. after the return statement and then right after the } of the hello() method. Which makes @After executing after @AfterReturning.