0

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?

10
  • Is there a bean created/configured that you can autowire for that type? Commented Feb 14, 2017 at 18:08
  • Yes. ServiceImpl1 and ServiceImpl2 are configured in the same applicationContext.xml Commented Feb 14, 2017 at 18:11
  • what error do you get? Commented Feb 14, 2017 at 18:13
  • Is there any link between ServiceImpl2 and ServiceImpl1? Does ServiceImpl2 implement Service1 as well? Commented Feb 14, 2017 at 18:15
  • Yes. ServiceImpl2 is autowired as a property of ServiceImpl1. Commented Feb 14, 2017 at 18:17

1 Answer 1

1

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());
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.