2013-04-16 1 views
4

TaskExecutor에서 작업을 실행하려면 Runnable 인터페이스를 구현하는 새 작업을 인스턴스화해야합니다. 이 문제를 해결하려면 create a new Spring Prototype Bean named Job "on Demand"을 입력하십시오.프로토 타입 (Spring LoC)간에 인스턴스를 공유하는 방법

그러나 내 응용 프로그램에서 Job에는 두 개의 필드 LocationChangerQueryTyper이 있습니다. 이 두 사람은 WebDriver 인스턴스WebDriverFactory으로 만들어 공유해야합니다.

이제 스프링으로 어떻게 설계 할 것인가?

UML of the Architecture

이 관련 코드 :

@Component 
@Scope("prototype") 
public class Job implements Runnable { 

    @Autowired 
    LocationChanger locationChanger; 

    @Autowired 
    QueryTyper queryTyper; 

    @Override 
    public void run() { 
     // at this point the locationChanger and 
     // queryTyper should share the same instance 
    } 

} 

@Component 
@Scope("prototype") 
public class LocationChanger { 

    @Autowired 
    @Qualifier(...) // For every new Job Created, the same WebDriver instance should be injected. 
    WebDriver webDriver 
} 

@Component 
@Scope("prototype") 
public class QueryTyper { 

    @Autowired 
    @Qualifier(...) // For every new Job Created, the same WebDriver instance should be injected. 
    WebDriver webDriver 
} 

public class WebDriverFactoryBean implements FactoryBean<WebDriver> { 
    @Override 
    public WebDriver getObject() throws Exception { 
     return // createdAndPrepare... 
    } 

    @Override 
    public boolean isSingleton() { 
     return false; 
    } 
} 

고마워요!

업데이트 1 : 가능한 솔루션은 작업 다음 @PostConstructLocationChangerQueryTyper받는 사람이 WebDriver를 주입을 WebDriver를 autowire하기 위해 수 있습니다. 그런데 손으로 철사. 나는 당신의 요구 사항을 이해한다면

@Component 
@Scope("prototype") 
public class Job implements Runnable { 

    @Autowired 
    LocationChanger locationChanger; 

    @Autowired 
    QueryTyper queryTyper; 

    @Autowired 
    WebDriver webDriver; 

    @PostConstruct 
    public void autowireByHand() { 
     locationChanger.setWebDriver(this.webDriver); 
     queryTyper.setWebDriver(this.webDriver); 
    } 
} 

// + remove all @Autowired WebDriver's from LocationChanger and QueryTyper 
+0

그래서'WebDriver'를 싱글 톤으로 원하십니까? – NilsH

+0

아니요, '작업'이 인스턴스화 될 때마다이 '작업'과 그 하위 작업자는 동일한 '웹 드라이브'를 공유해야합니다. 그래서 그것은 Singleton이 아닙니다 : ( – d0x

답변

2

, 당신은 WebDriverJobLocationChanger 사이에 공유 될 필요가있다. 따라서 범위가 prototype이 아니며 범위가 singleton이 아닙니다. 이 문제를 해결하기 위해, 나는 당신이 제안 당신이 손으로 그것을해야 하나 생각하거나

내가 생각하지 않는 Spring reference documentation

편집에 설명 된대로, 자신의 범위를 구현하기 위해 시도 할 수 당신은 "handwired"솔루션이 나쁜 BTW를 찾습니다.

+0

사용자 정의 범위에 대한 의견을 주셔서 감사합니다. 아마도 그럴 것입니다. 역동적 인 한정어에 대해서 생각해 보았습니다. 예 : LocationChanger와 QueryTyper는 Webdriver를 다음과 같이 표시해야합니다 :'@Autowire @Qualifier (어떻게 든이 문자열을 생성 된 작업 인스턴스에 연결) webDriver' annotation – d0x

+0

사용자 정의 범위가 가능해야합니다. 검색을 위해 인스턴스를 저장할 위치를 파악한 다음 "대화 ID"와 상호 연관시켜야합니다. – NilsH