SoFunction
Updated on 2025-04-09

SpringBoot dynamically calls interface to implement class methods based on parameters

In Spring Boot development, we often encounter the need to call different implementation methods of interfaces according to different parameters. This article will introduce in detail how to implement this function and handle the situation where the default method is called when the corresponding implementation class does not exist.

Requirement background

Suppose there is an interfaceI, it has three implementation classesABC, and all three implementation classes are used@ServiceAnnotations are registered in the Spring container, and the corresponding bean name istype + "Service". We need to use the parameters passed intypeDynamically call different implementation classesmMethod, iftypeIf the corresponding implementation class does not exist, the default method will be called.

Implementation steps

1. Define the interface

First, we define the interfaceI, this interface contains ammethod.

public interface I {
    void m();
}

2. Implement classes A, B, C

Create an interfaceIThree implementation categoriesABC, and use@ServiceAnnotations register them as Spring Beans.

import ;

@Service("AService")
public class A implements I {
    @Override
    public void m() {
        ("Executing method m in class A");
    }
}

@Service("BService")
public class B implements I {
    @Override
    public void m() {
        ("Executing method m in class B");
    }
}

@Service("CService")
public class C implements I {
    @Override
    public void m() {
        ("Executing method m in class C");
    }
}

3. Create a service factory class

Create a service factory classServiceFactory, used totypeParameters get the corresponding implementation class bean. If the corresponding bean cannot be found, a default implementation is returned.

import ;
import ;
import ;

@Component
public class ServiceFactory {

    @Autowired
    private ApplicationContext applicationContext;

    public I getService(String type) {
        String beanName = type + "Service";
        try {
            return (beanName, );
        } catch (Exception e) {
            // Here you can add the default processing logic            return new I() {
                @Override
                public void m() {
                    ("Executing default implementation of method m");
                }
            };
        }
    }
}

4. Controller class (optional)

If you need to trigger a method call through an HTTP request, you can create a controller class.MyController

import ;
import ;
import ;
import ;

@RestController
public class MyController {

    @Autowired
    private ServiceFactory serviceFactory;

    @GetMapping("/execute")
    public String execute(@RequestParam String type) {
        I service = (type);
        ();
        return "Method executed for type: " + type;
    }
}

5. Test class

Create a test classApplication,existrunTesting differently in the methodtypeThe service call, including a non-existenttypeto verify the default logic.

import ;
import ;
import ;
import ;

@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    private ServiceFactory serviceFactory;

    public static void main(String[] args) {
        (, args);
    }

    @Override
    public void run(String... args) {
        I serviceA = ("A");
        ();

        I serviceB = ("B");
        ();

        I serviceC = ("C");
        ();

        I defaultService = ("D");
        ();
    }
}

Code explanation

  • InterfaceI: Defined a methodm, for implementation class implementation.
  • Implementation ClassABC: The interfaces were implemented separatelyIofmMethod and use@ServiceAnnotation is registered as a bean.
  • Service factory categoryServiceFactory:passApplicationContextaccording totypeTry to get the corresponding implementation class bean, and if it cannot be found, it returns the default logic of an anonymous inner class implementation.
  • Controller classMyController: Provide an HTTP interface/execute, according to the incomingtypeCall the corresponding service method.
  • Test classApplication:existrunTesting differently in the methodtypeThe service call, including a non-existenttypeto verify the default logic.

Things to note

  • Can't directly@ServiceAnnotations are added to the interface because the interface itself cannot be instantiated and cannot be managed by Spring containers as a specific bean.
  • existServiceFactoryIn the class, when the corresponding one cannot be foundtypeWhen the bean is used, the returned default implementation can be modified and extended according to actual needs.

Through the above steps, we can use the parameters in the Spring Boot projecttypeDynamically call methods of different implementation classes of interfaces, and handle the situation where the default method is called when the corresponding implementation class does not exist.

This is the article about SpringBoot dynamically calling interface implementing class methods based on parameters. For more related contents of SpringBoot dynamically calling interface implementing class methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!