我偶然發現了使用@Cacheable創建的AOP代理在Spring 3.1.1中打破了依賴注入的情況。這是我的場景:@緩存中斷依賴注入
我有一個接口和一個類實現這個接口使用@Cacheable在實現的方法。
實施例接口:
public interface ImgService {
public byte[] getImage(String name);
}
實施例實現:
public class ImgServiceImpl implements ImgService {
@Cacheable(cacheName = "someCache")
public byte[] getImage(String name){//TODO};
protected String someOtherMethod(){//};
}
我也有JUnit測試類, - 其中一個噴射接口和一個實現:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:META-INF/spring.xml" })
public class ImgServiceTest {
@Inject
private ImgService;
}
和
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:META-INF/spring.xml" })
public class ImgServiceImplTest {
@Inject
private ImgServiceImpl;
}
接口的依賴注入工作正常。但是,當我開始在第二個測試類中注入實現時,我得到一個「注入自動裝載依賴關係失敗」。我能夠調試它,並且看起來ClassUtils.isAssignableValue()錯誤地將所需類型與代理類進行比較。它由DefaultListableBeanFactory調用。更奇怪的是,如果我從已實現的方法中刪除@Cacheable註釋並將其添加到其他protected/private方法,則依賴注入將再次正常工作。這是一個錯誤,處理這種情況的正確方法是什麼?
這裏是一個更很好的參考 - http://blog.springsource.org/2012/05/23/understanding-proxy-usage-in-spring/ – 2012-08-13 15:41:24