0

我的应用程序有一个如下界面。

public interface MainInterface
{
     void someMethod();
}

然后,我有这个接口的许多实现。

@Service    
public class ImplClass1 implements MainInterface
{
   @Override
   public void someMehtod()
   {
      //Execution of code
   }
}

@Service    
public class ImplClass2 implements MainInterface
{
   @Override
   public void someMehtod()
   {
      //Execution of code
   }
}

@Service
public class ImplClass3 implements MainInterface
{
   @Override
   public void someMehtod()
   {
      //Execution of code
   }
}

下面是一个控制器。

@Controller
public class MainController
{
     MainInterface implObj;

     @RequestMapping("service1")
     public void Service1Handler()
     {
         //Replace below with @Autowire
         implObj = new ImplClass1();
     }

     @RequestMapping("service2")
     public void Service1Handler()
     {
         //Replace below with @Autowire
         implObj = new ImplClass2();
     }

     @RequestMapping("service3")
     public void Service1Handler()
     {
         //Replace below with @Autowire
         implObj = new ImplClass3();
     }
}

正如在每种方法的评论中提到的,我想使用 spring 对其进行初始化。这只是一个例子。在我的实时应用程序中,我在控制器中有 12 个接口实现和 6 个方法。

您能否指导我如何在方法级别使用自动装配功能或建议任何其他最佳方式。

谢谢

4

1 回答 1

3

可以想到这两种方式——

@Controller
public class MainController
{
     @Autowired @Qualifier("impl1") MainInterface impl1;
     @Autowired @Qualifier("impl2") MainInterface impl2;
     @Autowired @Qualifier("impl3") MainInterface impl3;

     @RequestMapping("service1")
     public void service1Handler()
     {
          impl1.doSomething()
     }

     @RequestMapping("service2")
     public void Service1Handler()
     {
         //Replace below with @Autowire
          impl2.doSomething()
     }

     @RequestMapping("service3")
     public void Service1Handler()
     {
         //Replace below with @Autowire
           impl3.doSomething()
     }
}

或将其隐藏在工厂后面:

class MaintenanceInterfaceFactory{
     @Autowired @Qualifier("impl1") MainInterface impl1;
     @Autowired @Qualifier("impl2") MainInterface impl2;
     @Autowired @Qualifier("impl3") MainInterface impl3;
     getImplForService(String name){
        //return one of the impls above based on say service name..
     }
}
于 2012-07-13T21:03:25.773 回答