XML配置的Java配置类似物不起作用 [英] A Java config analog of XML configuration not working

查看:104
本文介绍了XML配置的Java配置类似物不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TL/DR:问题归结为创建自定义Spring范围,将具有prototype范围的Bean注入到具有proxyMode = ScopedProxyMode.TARGET_CLASS的单例中,但仍在配置的Java配置版本中获得单例(尽管它在XML上工作正常).

TL/DR: The problem boils down to creating a custom Spring scope, injecting a prototype-like scoped bean into a singleton with proxyMode = ScopedProxyMode.TARGET_CLASS but still getting a singleton in the Java config version of the configuration (whereas it works fine with XML).

更新:问题已解决,请参见答案.

UPDATE: Problem solved, see answer.

我正在使用jBehave为我们的Spring应用程序编写BDD测试方案.我们最近认为在执行测试方案时需要独立性(这意味着必须在每个方案之前重置测试上下文),并发现

I'm using jBehave to write BDD test scenarios for our Spring application. We recently thought that we need independence in executing test scenarios (meaning that test context has to be reset before each scenario) and found this article on the web that addresses exactly the issue we're dealing with.

本文建议创建一个自定义Spring Scenario范围,将其分配给表示测试上下文的类,并注入AOP代理而不是上下文文件.

The article advises creating a custom Spring Scenario scope, assigning it to the class that represents test context and injecting an AOP proxy instead of the context file.

我已经按照文章对所有内容进行了编码,并且效果很好,但是问题是我们需要Java配置而不是XML的方式,当我将所有更改都转换为Java config时,它就停止了工作-这意味着在每个测试方案之后,StoryContext中的Map都没有重置,并且包含先前方案中的值.

I've coded everything in accordance with the article and it worked great, but the thing is we need it in terms of Java config, not XML, and when I converted all the changes to Java config, it stopped working - meaning the Map in StoryContext was not reset after each test scenario and contained values from the previous scenario.

我的更改如下:

  • @Component批注标记ScenarioScope类:
  • marked the ScenarioScope class with the @Component annotation:
@Component
public class ScenarioScope implements Scope {

    private final ConcurrentMap<String, Object> cache = new ConcurrentHashMap<>();

    @BeforeScenario
    public void startScenario() {
        cache.clear();
    }

    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        return cache.putIfAbsent(name, objectFactory.getObject());
    }

    @Override
    public Object remove(String name) {
        return cache.remove(name);
    }

    @Override
    public void registerDestructionCallback(String name, Runnable callback) {
    }

    @Override
    public Object resolveContextualObject(String key) {
        return null;
    }

    @Override
    public String getConversationId() {
        return "scenario scope";
    }
}

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆