我有一个bean Item<T>需要在@Configuration课堂上自动装配.
@Configuration
public class AppConfig {
@Bean
public Item<String> stringItem() {
return new StringItem();
}
@Bean
public Item<Integer> integerItem() {
return new IntegerItem();
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试时@Autowire Item<String>,我得到以下异常.
"No qualifying bean of type [Item] is defined: expected single matching bean but found 2: stringItem, integerItem"
Run Code Online (Sandbox Code Playgroud)
我应该如何Item<T>在Spring中自动加载通用类型?
所以我在Spring 3.2中有很多泛型,理想情况下我的架构看起来像这样.
class GenericDao<T>{}
class GenericService<T, T_DAO extends GenericDao<T>>
{
// FAILS
@Autowired
T_DAO;
}
@Component
class Foo{}
@Repository
class FooDao extends GenericDao<Foo>{}
@Service
FooService extends GenericService<Foo, FooDao>{}
Run Code Online (Sandbox Code Playgroud)
遗憾的是,对于泛型的多个实现,自动装配会引发有关多个匹配bean定义的错误.我假设这是因为@Autowired类型擦除之前的进程.我找到或想出的每一个解决方案看起来都很难看,或者只是莫名其妙地拒绝工作.解决这个问题的最佳方法是什么?
我的Spring + Hibernate配置文件很小而且非常紧凑.我使用自动扫描来查找我的模型实体/ daos.
我不想在我的层次结构中为每个实体编写DAO + DAOImpl.
有些人可能有资格拥有自己的,如果他们与其他实体有复杂的关系,并且需要的不仅仅是基本的CRUD功能.但其余的......
有没有办法规避事实上的标准?
说,像通用DAO,ex:
http://www.ibm.com/developerworks/java/library/j-genericdao/index.html
然后我可以做类似的事情
GenericDao dao = appContext.getBean("genericDao");
dao.save(car);
dao.save(lease);
Run Code Online (Sandbox Code Playgroud)
这可能带注释吗?我不想在xml中配置任何东西.如果我不能在上面做,是否仍然可以有一个类似的GenericDaoImpl.java:
@Repository("carDao")
@Repository("leaseDao")
class GenericDaoImpl extends CustomHibernateDaoSupport implements GenericDao {
...
}
Run Code Online (Sandbox Code Playgroud)
然后
GenericDao dao = appContext.getBean("carDao");
dao.save(car);
dao = appContext.getBean("leaseDao"); //carDao is garbage coll.
dao.save(lease);
Run Code Online (Sandbox Code Playgroud)
这有用吗?