0

I’ve an interface BaseDao and other entity specific Dao interfaces which extend BaseDao.

public interface BaseDao<T extends RandomClass> {
 // some methods
}


public interface FooDao extends BaseDao<RandomClassImpl1>  {
// some methods
}

@Lazy
@Component(“fooDao”)
public class FooDaoImpl implements FooDao {

}

public interface BarDaoextends BaseDao<RandomClassImpl2>  {
// some methods
}

@Lazy
@Component(“barDao”)
public class BarDaoImpl implements BarDao {

}

I also created a config, where I created a bean which returns a Map where dao component name is key and dao component is value.

@Lazy
@Configuration
@Import({BarDaoImpl.class, FooDaoImpl.class })
public class DaoRepositoryConfig {

    @Bean(DAO_REPOSITORY)
    Map<String, BaseDao> DaoRepository(
            @Lazy @Qualifier(“fooDao”)
             BaseDao<RandomClassImpl1> foo,
            @Lazy @Qualifier(“barDao”)
             BaseDao<RandomClassImpl2> bar
    ) {
        Map<String, BaseDao> daoRepository = new HashMap<>();
        daoRepository.put(“fooDao”, foo);
        daoRepository.put(“barDao”, bar);
        return daoRepository;
    }

}

When I load this bean, I get a map of Dao names and dynamic proxy of corresponding implementation that I’ve imported in the config.

But when I try to type cast the proxy to immediate parent interface, it fails with ClassCastException.

(FooDao) daoRepo.get(“fooDao”) [ Here daoRepo.get(“fooDao”), returns proxy of FooDaoImpl which I could see in my debugger, but when I try to cast it to FooDao, ClassCast exception is thrown.

victini
  • 193
  • 1
  • 6
  • Possible duplicate of [Abstract DAO pattern and Spring's "Proxy cannot be cast to ..." problem!](https://stackoverflow.com/questions/3852564/abstract-dao-pattern-and-springs-proxy-cannot-be-cast-to-problem) – jingx Feb 02 '19 at 17:41
  • This guy is trying to type cast to a class, I am trying to type cast to interface. – victini Feb 02 '19 at 17:43
  • 1
    `(FooDao) daoRepo.get(“fooDao”)` defeats the purpose of ... a lot of things in your design. Also DaoRespository is basically doing the Spring context's job and hardly necessarily. – jingx Feb 02 '19 at 17:44
  • No, it doesn't defeat the purpose I believe. I am coding against interfaces and not implementation. There are two levels of interfaces in my example and implementation is being injected through spring only. – victini Feb 02 '19 at 17:49
  • Spring is capable of distinguishing between `Foo` and `Foo`. – chrylis -cautiouslyoptimistic- Feb 02 '19 at 18:14
  • Maybe they are loaded with different classloaderts and thus cannot be casted – jnr Feb 02 '19 at 19:50

0 Answers0