简体   繁体   English

在没有具体实现的接口的xml配置中创建spring bean

[英]Creating spring bean in xml configuration for an interface without concrete implementation

In my Spring 3.x application, I've couple of interfaces for which implementation is provided by some 3rd party libs included at run time. 在我的Spring 3.x应用程序中,我有几个接口,其中的实现是由运行时包含的一些第三方库提供的。 For the sake for development and unit testing, I'd like to inject some mock/dummy implementation of these interface. 为了开发和单元测试,我想注入一些这些接口的模拟/虚拟实现。 One obvious way to do is to define a concrete class implementing these interface and have it my test sources. 一个显而易见的方法是定义一个实现这些接口的具体类,并将它作为我的测试源。 Since I just want dummy classes for injection purpose, I was wondering if there is a way in Spring XML configuration through which I can define a <bean> element providing the interface class and let spring create a proxy class from that interface and inject it? 因为我只想要用于注入目的的虚拟类,所以我想知道Spring XML配置中是否有一种方法可以通过它来定义提供接口类的<bean>元素,让spring从该接口创建一个代理类并注入它?

I know I can do this with mockito like following, but in certain case I dont/cant use mockito and would like to see if this is possible only with Spring. 我知道我可以像mockito一样这样做,但在某些情况下,我不能/不能使用mockito,并希望看看这是否只有Spring才有可能。

<bean name="someServiceImpl" class="org.mockito.Mockito" factory-method="mock"> <constructor-arg value="foo.bar.SomeService" /> </bean>

The following is an example of the configuration you would use if you where using Java Config and it's based on JDK dynamic proxy. 以下是使用Java Config并且基于JDK动态代理的配置示例。

public class TestInvocationHandler implements InvocationHandler {


   @Override
   public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      return null;
   }
}

@Configuration
public class Config {

    @Bean
    @Profile("test")
    @Primary
    public SomeService someService() {
        return (SomeService) Proxy.newProxyInstance(Config.class.getClassLoader(), new Class[] {SomeService.class}, new TestInvocationHandler());
    }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM