Preparing for Java Interview?

My books Grokking the Java Interview and Grokking the Spring Boot Interview can help

Download PDF

Tuesday, March 2, 2021

Top 17 Spring AOP (Aspect-Oriented Programming) Interview Questions Answers

If you are preparing for Java and Spring Developer interviews or Spring professional certification then a good knowledge of Aspect-oriented Programming or AOP is required. It's a boring and tough topic but important from a Spring interview and Spring certification point of view and that's where these 15+ AOP interview questions come really handy. You can use them to revise key AOP concepts before any telephonic or face-to-face interview as well as to learn and explore more about Aspect-Oriented Programming. In this article, I am going to share frequently asked AOP interview questions and also tried to answer AOP questions give on the official Spring certification exam guide.

If you are a regular reader of this blog then you may know that I have sharing interview questions for Java developers on regular basis and earlier I have shared questions on Spring BootSpring MVCSpring CloudSpring Data JPA, and Spring security questions, which are all important for both Spring developer's interview as well as spring certification point of view. If you haven't read them yet, you can read them to prepare better for your next Spring interview. 

Aspect-Oriented Programming is a powerful technique to alter the behavior of your code to address the cross-cutting concern. You might be thinking about what is a cross-cutting concern and how does one can alter the behavior of your code, well it's not intuitive but it's possible. 

To be honest, AOP is a boring concept, at least for me, when I first read about AOP I didn't get it at all. I was lost in AOP jargons like Advice, JoinPoint, Pointcut, Weaving, and whatnot. It's only when I read the Spring in Action book and follow its Electric meter example, I was able to understand Aspect-Oriented Programming. 

I found that Aspect-oriented programming solves some problems which are not easier to solve by Object-oriented programming. It's not that you can't solve them using OOP but they are not elegant.

In order to understand AOP, you need to understand a thing called, cross-cutting concern, they are nothing but non-functional requirements which are used at multiple layers of your application. For example, logging is a cross-cutting concern as you need logging everywhere in your application. Similarly, security is a cross-cutting concern which requires at multiple places in your application.

You can easily use Inheritance or Delegation to solve those problems, I mean, define a class that does logging and security and let your business object implement them but that would make your business classes complex and cluttered. Aspect oriented programming solves those problems by inserting code for those cross-cutting patterns without you knowing about it.

For example, AOP can insert code at compile-time or when your class is loaded, or even when your methods are called. Those are actually called weaving and different AOP libraries have different weaving capabilities. For example, a powerful AOP library like the AspectJ can change the bytecode while a less powerful Spring AOP can use a proxy object to implement those crossing-cutting concerns.

Btw, if you are new to the Spring framework then I also suggest you join a comprehensive Spring framework course like Spring & Hibernate for Beginners (includes Spring Boot) to learn Spring in a more structured and hands-on way. This is a great course to learn three useful skills, Spring, Hibernate, and Spring Boot in just one course and I highly recommend it. 




Spring AOP Interview Questions and Answers

Without wasting any more of your time, let's jump into the boring world of AOP with some frequently asked AOP questions, I have tried to answer my best but if you want to learn more, I always suggest joining a good spring course or read my favorite spring boot, Spring in Action by Craig wallas. Those two are the best resources for any spring developer.


1. What is the concept of AOP?
AOP stands for Aspect-Oriented Programming and it helps decouple cross-cutting concerns from the object that they affect. It's similar to Dependency Injection in the sense that DI helps decouple an application's object from each other.


2. Which problem AOP solves?
AOP helps in separating cross-cutting concerns from the business logic, which results in cleaner code and also helps developers to focus on building business logic.


3. What is a cross-cutting concern?
crossing cutting concern is common functionality that is scattered around multiple places. They are common and you aspect they should be structured but they are not, which makes them hard to manage. AOP helps them to manage the cross-cutting concerns.


4. Can you name three typical cross-cutting concerns?
There are many cross-cutting concerns but the three most common ones are logging, security, and caching.


5. What two problems arise if you don’t solve a cross-cutting concern via AOP?
It will make your code clutters as concerns will be spread across your application, which will be hard to manage. 


6. What is a pointcut, a join point, advice, an aspect, weaving?
These are common AOP terms that every programmer needs to know as you just cannot work in AOP without knowing these terms. They are the backbone of AOP but at the same time they are not intuitive and boring and hard to understand, anyway, let's try to learn them.

Aspect
An aspect is a common feature that's typically scattered across methods, classes, object hierarchies, or even entire object models.

Advice
This is the functionality that is applied using AOP. It defines the "what" and "when" part of the aspect.

JoinPoint
These are the places where you can apply your "advice". There can be multiple join points in the flow of a program

Pointcut
They are used to find the join points where advice needs to be applied. You can define Pointcut by class name or method name, or you can use regular expressions to find different join points to apply your advice.

Weaving
This is a process of applying aspects to a target object to create a new proxied object. In simple words, it's a process when the AOP library or framework adds dynamic code to alter the behavior of your program. For example, compile-time weaving can add new code at compile time.


7. How does Spring solve (implement) a cross-cutting concern?
Spring uses proxy objects to implement the method invocation interception part of Aspect-Oriented Programming. Such proxy objects wrap the original Spring bean and intercept method invocations as specified by the set of pointcuts defined by the cross-cutting concern. 

This means when you call a method on a spring bean, the method on a proxy object is called which extends the original spring bean. It then does whatever it has to do as part of implementing cross-cutting concern like logging or security check and then call the original method.


8. What are the two proxy-types used in Spring AOP?
There are two dynamic proxy techniques used in spring AOP, JDK dynamic proxy and CGLIB proxy

1. JDK dynamic proxy
In the case of JDK dynamic proxy, Proxies are created at runtime by generating a class that implements all the interfaces that the target object implements. Since standard Java features are used, no additional libraries are required. It's also worth noting that JDK dynamic proxies are the default proxy mechanism used by Spring AOP.

2. CGLIB proxy
This is another way to generate Proxy objects in Spring, it requires a third-party library called CGLIB which is included in the spring-core JAR. CGLIB proxies are created by generating a subclass of the class implementing the target object.

The CGLIB proxy mechanism will be used by Spring AOP when the Spring bean for which to create a proxy does not implement any interfaces. It is also possible to instruct Spring AOP to use CGLIB proxies by default using annotation @EnableAspectJAutoProxy(proxyTargetClass = true)

Another worth noting thing is that Spring Java configuration classes, annotated with @Configuration, will always be proxied using CGLIB. 

If you want to learn more about this question, you can also check Dominik Cebula's Spring Professional Certification Exam Tutorial - Module 02 where he had answered all AOP-related questions from the Spring Professional exam guide. This is a great course for anyone preparing for spring certification. 

Top 17 Spring Aspect-Oriented Programming (AOP) Interview Questions Answers



9. What are the limitations of the two proxy-types used in Spring AOP?
As stated in the last question, Spring AOP uses JDK proxy and CGLIB proxies and both proxy objects have the same limitation: the invocation of advised methods on self.

If a method in the proxy calls another method in the proxy, and both match the pointcut expression of advice, the advice will be executed only for the first method. This is the proxy’s nature: it executes the extra behavior only when the caller calls the target method.

Apart from that here are some more limitation of each proxy types:

JDK Dynamic Proxies Limitations
  • Your target object must implement an interface.
  • Only public methods will be proxied.
  • Any methods found in the target object but not in any interface implemented by the target object cannot be proxied.
  • Aspects can be applied only to Spring Beans. That means even if Spring AOP is not set to use CGLIB proxies if a Join Point is in a class that does not implement an interface, Spring AOP will try to create a CGLIB proxy.

CGLIB Proxy Limitations
  • Class and Methods cannot be final
  • Only public and protected methods can be proxied.
  • It takes more time to create a proxy object, although it has better performance
These are some notable differences between JDK proxies and CGLIB proxies. 



10. What visibility must Spring bean methods have to be proxied using Spring AOP?
Only public methods of Spring beans will be proxied Additionally the call to the public method must originate from outside of the Spring bean.


10. How many advice types do Spring support? Can you name each one?
Spring Aspects can work with five types of advice:

@Before
This advice functionality takes place before the advised method is invoked.

@After
The advice functionality takes place after the advised method completes

@AfterReturning
This advice functionality is implemented after the advised method successfully completes.

@AfterThrowing
This advice functionality is implemented after the advised method throws an Exception.

@Around
This advice wrap the advised method, provided some functionality before and after the advised method is invoked


11. What are they used for?
Now that you know different types of advice you can actually think where can they be used, nonetheless here are some points

@Before
Since before advice always proceed to the join point unless execution is thrown from within the advice code you can use this for Access control, security, and Statistics

@AfterReturning
In this advice functionality takes place after the execution of a join point has completed without throwing any exceptions and you can use this for statistics and Data validation

@AfterThrowing
This is invoked after the execution of a join point that resulted in an exception being thrown
Error handling you can use this to send alerts to your monitoring tools when an error has occurred as well for error recovery.

@After
This advice will execute after a join point execution, no matter how the execution ended (even exception happens). You can use this for releasing resources just like the final clause in Java.

@Around
This is multi-purpose advice and can be used for all of the use-cases for AOP.


12. Which types of advice you can use to try and catch exceptions?
You can use both @Around and @AfterThrowing advice in this case but only @Around advice allows you to catch exceptions in the advice that occur during the execution of a join point.


13. What is the JoinPoint argument used for?
A JoinPoint argument can be used to retrieve additional information about the join point during execution. If used, JoinPoint needs to be the first parameter of Advice, only, in that case, Spring Framework will inject JoinPoint into advice method.

JoinPoint is supported in @Before, @After, @AfterReturning, and @AfterThrowing advice and you can use JointPoint different kinds of information like:
  • The string representation of JoinPoint
  • Arguments of JoinPoint (for example Method Arguments)
  • Signature of JoinPoint (for example Method Signature)
  • Type of JoinPoint
  • Target object being proxied


15. What is a ProceedingJoinPoint? Which advice type is it used with?
The ProceedingJoinPoint class is a parameter to an @Around advice. When used it should be the first parameter of a method implementing an around advice.
When it’s ready to pass control to the advised method, it will call ProceedingJoinPoint’s proceed() method, which is used to execute the actual method.

Here is an example of using ProceedingJoinPoint advice:

@Aspect
public class Book {

  @Pointcut("execution(** libary.Book.read(..))")
  public void read() {}

  @Around("read()")
  public void sitAndRead(ProceedingJoinPoint jp) {
    try {
      System.out.println("sit down and relax");
      jp.proceed(); //this is important, you must call proceed on ProceedingJoinPoint
     } catch (Throwable e) {
       System.out.println("sorry, other time");
     }
   }
}


16. Can you name some popular Aspect-oriented programming libraries?
Here is a list of some of the popular AOP libraries you can use to implement AOP in your application:
1. AspectJ
2. JBoss AOP
3. Spring AOP


17. What are the different types of Weaving which is available in AOP?
There are many types of weaving available in different AOP libraries like compile-time weaving, weaving at the time of class loading, or weaving when the method gets called.


That's all about the frequently asked Spring AOP Interview Questions. While Spring AOP is not a very popular topic on Java and Spring Boot interviews, it's very important for anyone who wants to master the spring framework. AOP plays an important part in the Spring framework and it will help you understand how the Spring framework works behind the scene. If you want to understand the magic of Spring Framework and Spring Boot, learning Spring AOP will be key.


Further Learning
Learn Spring: The Master Class by Baeldung


 Other Java and Spring articles you may like
  • Top 5 courses to learn Spring Boot and Spring Cloud ( courses)
  • 5 Courses to learn Spring Cloud and Microservices (courses)
  • 15 Microservices Interview questions (answers)
  • 130+ Java Interview Questions for Practice (java questions)
  • 5 Best Courses to learn Hibernate and JPA (best courses)
  • 3 Best Practices Java Programmers can learn from Spring (best practices)
  • 10 Spring MVC annotations Java developers should learn (annotations)
  • 10 Tools Java Developers use in their day-to-day life (tools)
  • 10 Courses to learn Spring Security with OAuth 2 (courses)
  • Top 5 Books and Courses to learn RESTful Web Service (books)
  • 5 Spring Boot Annotations for full-stack Java developers (tutorial)
  • 3 ways to change Tomcat port in Spring Boot (tutorial)
  • Top 5 Courses to learn Microservices in Java? (courses)
  • 10 Advanced Spring Boot Courses for Java Programmers (courses)

Thanks for reading this article so far. If you find these Spring AOP Interview questions and answers useful then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you want to learn about Spring Framework and looking for a free online course to learn Spring Fundamentals then I also recommend you to join the Spring Framework And Dependency Injection For Beginners [FREE] course on Udemy. It's one of the best free courses to learn Spring basics for Java developers. 

No comments :

Post a Comment