[英]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. 我在编写JUnit测试时遇到一些奇怪的问题,我能够自动连接一个服务实现类,但不能自动连接另一个服务实现类。 The applicationContext configuration of ServiceImpl1 and ServiceImpl2 are similar.
ServiceImpl1和ServiceImpl2的applicationContext配置类似。
@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. 这里ServiceImpl2是Service2的实现类。 How can I get the instance of ServiceImpl2 from service2?
如何从service2获取ServiceImpl2的实例?
I would like to test some methods of ServiceImpl2 which are not in interface Service2. 我想测试一些ServiceImpl2的方法,这些方法不在Service2接口中。
Or if you know how I can make the Autowired work for class ServiceImpl2? 或者,如果您知道我如何使Autowired可以用于ServiceImpl2类?
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/
我在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()); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.