David Ruan
David Ruan

Reputation: 794

How to get an implementation class instance from the proxy instance in Java

I have some weird problem while writing JUnit test that I'm able to Autowired one service implementation class but not able to Autowired another one. The applicationContext configuration of ServiceImpl1 and ServiceImpl2 are similar.

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

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

But this one will work

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

Here ServiceImpl2 is the implementation class of Service2. How can I get the instance of ServiceImpl2 from service2?

I would like to test some methods of ServiceImpl2 which are not in interface Service2.

Or if you know how I can make the Autowired work for class ServiceImpl2?

Upvotes: 0

Views: 1096

Answers (1)

David Ruan
David Ruan

Reputation: 794

I find the answer from another post.

I find good for me solution on 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
  }
}

Usage

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

Upvotes: 1

Related Questions