SpringMVC通過ApplicationContext得到動態代理報錯問題

報錯:

java.lang.ClassCastException: com.sun.proxy.$Proxy91 cannot be cast to com.zhl.services.book.AnshaoServic

解決辦法:

不能用接口的實現類(UserServiceImpl01_AOP)來轉換Proxy的實現類,它們是同級,應該用共同的接口來轉換

dao:

public interface AnshaoDao 

service:

@Service
public class AnshaoService implements AnshaoDao


解決方案:

public class AnshaoServiceTest {

    private ApplicationContext applicationContext;

    @Before
    public void setUp() throws Exception {
        applicationContext = new FileSystemXmlApplicationContext("classpath:spring/applicationContext.xml");
    }

    @Test
    public void test() {
        //錯誤代碼:
        AnshaoService anshaoService = (AnshaoService) applicationContext.getBean("anshaoService");
        
        //正確代碼
        AnshaoDao anshaoDao = (AnshaoDao) applicationContext.getBean("anshaoService");
        anshaoDao.addAll();
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章