Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Making a class implement an interface at runtime using an introduction


An introduction allows us to make a Java class (we will refer to it as the target class) implement an interface at runtime. With Spring AOP, introductions can be applied only to Spring beans (controllers, services, and so on). In this recipe, we will create an interface, its implementation, and make a Spring controller implement that interface at runtime using that implementation. To check whether it's working, we will also add a before advice to the controller method to execute a method from the interface implementation.

Getting ready

We will use the aspect class defined in the Creating a Spring AOP aspect class recipe.

How to do it…

Here are the steps for using an introduction:

  1. Create the Logging interface:

    public interface Logging {
      public void log(String str);
    }
  2. Create an implementation class for it:

    public class LoggingConsole implements Logging {
    
      public void log(String str) {
        System.out.println(str);
      }
    }
  3. In your...