编程语言
首页 > 编程语言> > java – 如何在Prototypes之间共享实例(Spring LoC)

java – 如何在Prototypes之间共享实例(Spring LoC)

作者:互联网

要在TaskExecutor中运行作业,我需要实例化实现Runnable接口的新作业.要解决这个问题,我会create a new Spring Prototype Bean named Job “on Demand”.

但在我的应用程序中,Job有两个字段LocationChanger和QueryTyper.这两个应该共享由WebDriverFactory创建的同一WebDriver实例.

现在的问题是如何用Spring设计它?

这是相关代码:

@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:
一种可能的解决方案可能是仅在Job中自动装载WebDriver,然后在@PostConstruct中将此WebDriver注入LocationChanger和QueryTyper.但后来我手工连线.

@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

解决方法:

如果我了解您的要求,您需要在Job和LocationChanger之间共享WebDriver.所以它不是原型范围,也不是单例范围.为了解决这个问题,我认为您要么必须按照您的建议手动完成,要么您可以尝试实现自己的范围,如Spring reference documentation中所述

编辑

我不认为你“handwired”解决方案看起来不好BTW.

标签:java,spring,spring-ioc
来源: https://codeday.me/bug/20190703/1370296.html