我的问题是如何在类X中访问bean,即在类Y中自动装配?
我使用弹簧靴,我有2个控制器:
@Controller
public class OwnerController {
@Autowired
StandardDaoAction<Owner> ownerDao;
和另一个
@Controller
public class VisitController {
@Autowired
StandardDaoAction<Pet> petDao;
现在我需要在VisitController类中添加StandardDaoAction ownerDao bean,但是当我使用简单的autowired时,我会得到异常,因为定义了同一个类的多个bean,而spring不知道该怎么做。我试着以某种方式用@Qualifier来区分它们,但它没有用,或者我搞砸了。
这是一个非常基本的问题,但我坚持下去,无法找到解决方案
确定所以我得出结论,核心问题在于我的dao&s和接口的实现,也就是说我使用泛型有问题:
我的界面:
public interface StandardDaoAction<T> {
public T get(int id);
public void remove(int id);
public void add(T Type);
public void update(T type);
public List<T> getAll();
}
两个类实现接口:
@Repository
public class PetDaoImpl implements StandardDaoAction<Pet> {
@PersistenceContext
EntityManager em;
@Transactional
public Pet get(int id) {
return em.find(Pet.class, id);
}
@Transactional
public void remove(int id) {
em.remove(id);
}
@Transactional
public void add(Pet pet) {
em.persist(pet);
}
@Transactional
public void update(Pet pet) {
em.merge(pet);
}
@SuppressWarnings("unchecked")
@Transactional
public List<Pet> getAll() {
return em.createQuery("from Pet").getResultList();
}
}
@Repository
public class OwnerDaoImpl implements StandardDaoAction<Owner> {
@PersistenceContext
EntityManager em;
@Transactional
public Owner get(int id) {
return em.find(Owner.class, id);
}
@Transactional
public void remove(int id) {
em.remove(get(id));
}
@Transactional
public void add(Owner owner) {
em.persist(owner);
}
@Transactional
public void update(Owner owner) {
em.merge(owner);
}
@SuppressWarnings("unchecked")
@Transactional
public List<Owner> getAll() {
return em.createQuery("From Owner").getResultList();
}
}
当我添加:
@Controller
public class VisitController {
@Autowired
StandardDaoAction<Pet> petDao;
@Autowired
StandardDaoAction<Owner> ownerDao;
这是错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'visitController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: pl.kaczynski.dao.StandardDaoAction pl.kaczynski.controller.VisitController.ownerDao; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [pl.kaczynski.dao.StandardDaoAction] is defined: expected single matching bean but found 3: ownerDaoImpl,petDaoImpl,vetDaoImpl
还有vetDaoImpl,因为还有另一个控制器:
@Controller
public class VetListController {
@Autowired
StandardDaoAction<Vet> vetDao;
也实现了界面,如上所示。
所以只要我有一个实现StandardDaoActions接口的bean,它就可以工作,因为它按类型自动装配,但是当我在不同的控制器中添加另一个自动装配的bean时,会发生错误。
答案 0 :(得分:1)
由于类型擦除,您将有两个类型为StandardDaoAction
的bean。
@Autowired private PetDaoImpl petDao
@Autowired @Qualifier("petDaoImpl") private StandardDaoAction<Pet> petDao