如何从Java中的代理实例获取实现类实例

时间:2017-02-14 18:05:20

标签: java spring interface implementation autowired

在编写JUnit测试时,我有一些奇怪的问题,我可以自动连接一个服务实现类,但不能再自动连接另一个。 ServiceImpl1和ServiceImpl2的applicationContext配置类似。

@Autowired 
private ServiceImpl1 serviceImpl1;   //This one works.

@Autowired 
private ServiceImpl2 serviceImpl2;   //This one doesn't work.

但是这个会起作用

@Autowired 
private Service2 service2;   //This one works.

这里ServiceImpl2是Service2的实现类。如何从service2获取ServiceImpl2的实例?

我想测试一些不在Service2接口中的ServiceImpl2方法。

或者,如果您知道如何为ServiceImpl2类启用Autowired工作?

1 个答案:

答案 0 :(得分:1)

我从另一篇文章中找到答案。

  

我认为对我有好处的解决方案   http://www.techper.net/2009/06/05/how-to-acess-target-object-behind-a-spring-proxy/

@SuppressWarnings({"unchecked"})
protected <T> T getTargetObject(Object proxy, Class<T> targetClass) throws Exception {
  if (AopUtils.isJdkDynamicProxy(proxy)) {
    return (T) ((Advised)proxy).getTargetSource().getTarget();
  } else {
    return (T) proxy; // expected to be cglib proxy then, which is simply a specialized class
  }
}
     

用法

@Override
protected void onSetUp() throws Exception {
  getTargetObject(fooBean, FooBeanImpl.class).setBarRepository(new MyStubBarRepository());
}