简体   繁体   English

如何使用@Configuration类为jerseytest覆盖在xml中定义的spring bean定义

[英]How to override spring bean definition defined in xml with @Configuration class for jerseytest

I have been trying to figure this out for some time but am not able to get it to work. 我一直在试图解决这个问题,但是我无法让它发挥作用。 I am using spring version 3.2.3.RELEASE and I think this may be causing some of my issues. 我使用的是Spring版本3.2.3.RELEASE,我认为这可能会导致我的一些问题。 My goal is to override the bean defined in the xml with a configuration file that has imported the configuration.The last class listed is my TestAppConfig where I import the AppConfig and want to simply override the bean implementation with mock implementations. 我的目标是使用已导入配置的配置文件覆盖xml中定义的bean。列出的最后一个类是我的TestAppConfig,我在其中导入AppConfig并希望简单地使用模拟实现覆盖bean实现。 However this is not working for me. 但这不适合我。 Any suggestions would be appreciated. 任何建议,将不胜感激。

This is my bean definition class where I define a couple of beans. 这是我的bean定义类,我定义了几个bean。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

    <import resource="rest-common.xml"/>

    <context:property-placeholder  location="classpath:module.properties"/>


    <bean name="vcheckResource" class="com.foo.vcheck.resources.VcheckResource" />

    <bean name="vcheckProvider" class="com.foo.vcheck.provider.VcheckProvider" />

    <bean name="Vcheck" class="com.foo.vcheck.provider.VcheckMessageRouter" />

</beans>

Here is the production @Configuration class where I import the bean configuration file. 这是生产@Configuration类,我在其中导入bean配置文件。

@Configuration
@Import(RestAppConfig.class)
@ImportResource({VcheckAppConfig.ModuleResources})
public class VcheckAppConfig {

    public static final String ModuleResources =  "classpath:bcpbx-api-vcheck-rest-beans.xml";

}

This is my Testing configuration class where I want to override the implementations with my Mockito mocks and in the unit test the production code should be injected with these mock classes. 这是我的测试配置类,我想用我的Mockito模拟覆盖实现,在单元测试中,生产代码应注入这些模拟类。 However the beans in the xml configuration are not being overridden for whatever reason. 但是,无论出于何种原因,都不会覆盖xml配置中的bean。 If I remove the import it will use the beans from this class so I know this is working. 如果我删除导入它将使用此类中的bean,所以我知道这是有效的。 Is this possible with 3.x version of spring? 这有可能与3.x版本的弹簧?

@Configuration
@Import(VcheckAppConfig.class)
public class TestAppConfig {

    @Bean
    public Account testAccount() {
        return new Account("TEST_ACCOUNT", new Vendor("TEST_VENDOR"));
    }

    @Bean(name ="vcheckResource")
    public VcheckResource vcheckResource() {
        return new VcheckResource(vcheckProvider(), new UUIDGenerator());
    }

    @Bean(name="vcheckProvider")
    public IVcheckProvider vcheckProvider() {
        System.out.println("CALLIGN GET MOCK");
        return Mockito.mock(VcheckProvider.class);
    }

    @Bean
    public IMessageRouter messageRouter() {
        return Mockito.mock(IMessageRouter.class);
    }

    @Bean
    public ICommandResponseCallbackRegistry responseRegistry() {
        return Mockito.mock(ICommandResponseCallbackRegistry.class);
    }

}

It appears there is no way to do this with spring. 看来春天无法做到这一点。

How do I override a Spring bean definition yet still reference the overridden bean? 如何覆盖Spring bean定义但仍然引用重写的bean?

I converted to use spring-mockito and used another bean xml file to add the mocks. 我转换为使用spring-mockito并使用另一个bean xml文件来添加模拟。 Then import both of the configuration xml files. 然后导入两个配置xml文件。 This works fine with spring mockito in my unit test. 这在我的单元测试中与spring mockito一起工作正常。 I did have to change my version of mockito to use 1.9.0 to be compatable with spring mockito. 我确实需要更改我的mockito版本才能使用1.9.0与spring mockito兼容。

https://bitbucket.org/kubek2k/springockito/wiki/Home https://bitbucket.org/kubek2k/springockito/wiki/Home

@Configuration
@ImportResource({VcheckAppConfig.ModuleResources, TestAppConfig.MockModuleResources})
public class TestAppConfig {

    public static final String MockModuleResources = "classpath:bcpbx-api-vcheck-rest-beans-mock.xml";

    @Bean
    public Account testAccount() {
        return new Account("TEST_ACCOUNT", new Vendor("TEST_VENDOR"));
    }
}

Here is my example mock where I override the implementation for my provider with the simple mock. 这是我的示例模拟,我用简单的模拟覆盖我的提供者的实现。 I was able to 我本来可以

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mockito="http://www.mockito.org/spring/mockito"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.mockito.org/spring/mockito http://www.mockito.org/spring/mockito.xsd">

    <mockito:mock id="vcheckProvider" class="com.foo.vcheck.provider.VcheckProvider"  />

</beans>

As a side note I am going to post this also because it was a nice solution to allow me to do jersey testing with spring dependency injection. 作为旁注,我将发布这个也是因为这是一个很好的解决方案,允许我做春季依赖注入的球衣测试。

public abstract class AbstractSpring3JerseyTest implements ApplicationContextAware {

    private static final Logger logger = Logger.getLogger(AbstractSpring3JerseyTest.class.getName());

    private JerseyTest jerseyTest;

    private ApplicationContext applicationContext;

    @Before
    public void setup() throws Exception {
        jerseyTest.setUp();
    }

    @After
    public void tearDown() throws Exception {
        jerseyTest.tearDown();
    }

    protected Application configure(ApplicationContext appContext) {
        ResourceConfig resourceConfig = ResourceConfig.forApplication(new RestApplication());
        resourceConfig.property("contextConfig", appContext);
        resourceConfig.register(SpringLifecycleListener.class).register(RequestContextFilter.class);
        resourceConfig.packages(getResourcePackages());
        resourceConfig.register(new RestAuthenticationFilter());
        resourceConfig.property(ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, "true");
        resourceConfig.register(new LoggingFilter(logger, 20000));

        return resourceConfig;
    }

    protected abstract String[] getResourcePackages();

    public static void setDebugLevel(Level level) {
        Logger anonymousLogger = LogManager.getLogManager().getLogger("");
        Handler[] handlers = anonymousLogger.getHandlers();
        anonymousLogger.setLevel(level);
        for (Handler h : handlers) {
            if (h instanceof ConsoleHandler)
                h.setLevel(level);
        }
    }

    public final WebTarget target() {
        return jerseyTest.target();
    }

    public final WebTarget target(final String path) {
        return jerseyTest.target().path(path);
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * Set the ApplicationContext that this object runs in. Normally this call
     * will be used to initialize the object.
     * <p>
     * Invoked after population of normal bean properties but before an init
     * callback such as
     * {@link org.springframework.beans.factory.InitializingBean#afterPropertiesSet()}
     * or a custom init-method. Invoked after
     * {@link ResourceLoaderAware#setResourceLoader},
     * {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
     * {@link MessageSourceAware}, if applicable.
     * 
     * @param applicationContext
     *            the ApplicationContext object to be used by this object
     * @throws ApplicationContextException
     *             in case of context initialization errors
     * @throws BeansException
     *             if thrown by application context methods
     * @see org.springframework.beans.factory.BeanInitializationException
     */
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        jerseyTest = new JerseyTest(configure(applicationContext)) {
        };
    }
}

Here is a simple test just to verify that all of the parts are working. 这是一个简单的测试,只是为了验证所有部件是否正常工作。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestAppConfig.class } )
public class TestVcheckResourceJersey extends AbstractSpring3JerseyTest {


    @Inject
    IVcheckProvider vcheckProvider;

    @Test
    public void testCheckNpanxx() throws ProviderException {
        Assert.assertNotNull(vcheckProvider);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在基于java的配置中覆盖xml定义的spring bean - Override xml-defined spring bean in java-based configuration 配置 class 中的 Spring bean 未在.xml 文件中定义的 bean 中自动装配 - Spring bean in Configuration class not being autowired in a bean defined in .xml file 用于覆盖 XML 定义的 Bean 注释 - Spring - Bean Annotation to override XML definition - Spring 如何将 XML 的 bean 定义移动到 @Configuration 注解的 class - How to move XML bean definition to @Configuration annotated class 如何在Spring配置中为所有子类提供单个bean定义? - How to provide single bean definition for all child class in spring configuration? 覆盖春豆的定义 - Override spring bean definition 如何从JerseyTest子类访问Spring Bean - How to access Spring Bean from JerseyTest subclass 我可以覆盖使用类路径扫描定义的Spring bean定义吗? - Can I override a spring bean definition defined using classpath scan? 在类路径资源[spring / database / DataSource.xml]中定义名称为&#39;dataSource&#39;的bean定义无效 - Invalid bean definition with name 'dataSource' defined in class path resource [spring/database/DataSource.xml] 如何使用自定义bean定义在集成测试中覆盖Spring Bean? - How to override Spring Bean in integration test with custom bean definition?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM