2012-07-13 2 views
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(); 
    } 
} 

각 메소드의 주석에서 언급했듯이 나는 봄을 사용하여 초기화하려고합니다. 이것은 단지 예입니다. 내 실시간 응용 프로그램에서 나는 인터페이스의 12 구현 및 컨트롤러의 6 메서드가 있습니다.

방법 수준에서 자동 배선 기능을 사용하거나 다른 최상의 방법을 제안 할 수있는 방법을 안내해주십시오.

감사

+0

내가 컨트롤러 sigletone이 될 것이라고 우려하고 당신은 당신의 인터페이스를 만들었습니다 컨트롤러의 인스턴스이며 각 메소드에서 구현을 변경하려고합니다. –

+0

네, 맞습니다. –

답변

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.. 
    } 
} 
+0

답장을 보내 주셔서 감사합니다. 내가 말했듯이 나는 12 개의 인터페이스를 구현 했으므로 첫 번째 옵션에 따라 12 개의 클래스 변수를 생성하기가 어려울 것이다. 하지만 당신의 두 번째 해결책을 따를 수 있습니다. 다시 한 번 감사드립니다! –

관련 문제