简体   繁体   中英

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. 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?

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.

<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.

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());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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