Spring Certified Professional 2023 · Free Practice Question Medium
Question 14
______ is linking aspects with other application types or objects to create an advised object.
-
A
Deferring
-
B
Threading
-
C
Pooling
-
D
Weaving
Reveal correct answer
Correct answer: D
Explanation
Weaving: linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.
Here's an example code snippet that demonstrates AOP weaving in Spring:
- // Aspect class
- @Aspect
- @Component
- public class LoggingAspect {
- @Before("execution(* com.example.service.*.*(..))")
- public void beforeMethodExecution(JoinPoint joinPoint) {
- // Logging logic
- System.out.println("Before method execution: " + joinPoint.getSignature().getName());
- }
- }
- // Service class
- @Component
- public class MyService {
- public void doSomething() {
- // Business logic
- System.out.println("Doing something...");
- }
- }
- // Main class
- @SpringBootApplication
- public class Application {
- public static void main(String[] args) {
- SpringApplication.run(Application.class, args);
- // Getting the bean and invoking the method
- MyService myService = applicationContext.getBean(MyService.class);
- myService.doSomething();
- }
- }
In the above code, the LoggingAspect class is an aspect that defines a @Before advice. It intercepts the execution of methods in the com.example.service package and logs a message before the method execution. This is achieved through AOP weaving, where the aspect is woven into the target object (in this case, MyService class) at runtime.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
