spring 服务如何识别控制器

iqih9akk  于 11个月前  发布在  Spring
关注(0)|答案(2)|浏览(83)

我有一个Sping Boot 应用程序,它有这样的情况:

Controller A { service.call()}
Controller B { service.call()}

字符串
取决于使用的控制器,我需要在服务中实现自定义逻辑。Spring生态系统允许在没有任何外部方法的情况下实现它吗,比如ID,不同的服务实现等。
如何让服务知道使用了哪个控制器A或B?

jgovgodb

jgovgodb1#

你可以使用反射技巧来解决这个问题,但是真的没有理由这样做。解决方案很简单:如果你需要不同的功能,使用不同的方法:

class SomeService {
  void callFromA() {
    // A specific stuff
    call()
  }

  void callFromB() {
    // B specific stuff
    call()
  }

  private void call() { 
    // shared logic
  }
}

字符串
更新:我认为这是显而易见的,但现在你可以使用它:

class ControllerA {
  private final SomeService service;
  void someMethod() { service.callFromA(); }
}
class ControllerB {
  private final SomeService service;
  void someMethod() { service.callFromB(); }
}

rjee0c15

rjee0c152#

我对Spring生态系统没有任何概念,但Java本身有一个解决方案。

public class SomeService {

     public void someMethod(){

       // this will fetch all the information about current thread
       StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();

       // third element of the array will contain caller class name
       String callerClassName = stackTrace[2].getClassName();

       // now you can perform whatever operation based on callerClassName
       if(callerClassName.equals("A")){
          //doThis
       }else{
          //doThat
       }
    }
}

字符串

相关问题