1

我使用 jpa、eclispelink 和 spring 3。我有 UserDAO 接口:

  public interface UserDAO {
    public void saveUser(User user);
  }

和实现类:

@Service
@Transactional
public class UserDAOImpl implements UserDAO{

@PersistenceContext
EntityManager em;

@Override
public void saveUser(User user) {
    em.persist(user);
}


当我启动应用程序时出现错误:

HTTP Status 500 - Servlet.init() for servlet appServlet threw exception<br>
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cartController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: foo.endpoints.UserEndpoint foo.controller.CartController.userEndpoint; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userEndpoint': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: foo.dao.UserDAOImpl foo.endpoints.UserEndpoint.userDAO; nested exception is java.lang.IllegalArgumentException: Can not set foo.dao.UserDAOImpl field foo.endpoints.UserEndpoint.userDAO to com.sun.proxy.$Proxy16

org.springframework.beans.factory.BeanCreationException: Could not autowire field: foo.endpoints.UserEndpoint foo.controller.CartController.userEndpoint; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userEndpoint': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: foo.dao.UserDAOImpl foo.endpoints.UserEndpoint.userDAO; nested exception is java.lang.IllegalArgumentException: Can not set foo.dao.UserDAOImpl field foo.endpoints.UserEndpoint.userDAO to com.sun.proxy.$Proxy16


但如果我不实现接口:

 @Service
 @Transactional
 public class UserDAOImpl {
 @PersistenceContext
 EntityManager em;
  public void saveUser(User user) {
  em.persist(user);
  }


一切正常。我不明白。也许它与@Override 方法有关?谢谢

4

1 回答 1

4

如果为 bean 定义接口,则必须注入接口的实例,而不是具体类的实例:

@Autowired
private UserDAO userDAO;

并不是

@Autowired
private UserDAOImpl userDAOImpl;

因为实际的 bean 实例是一个 JDK 动态代理,它实现了接口并调用你的实现。它不是 UserDAOImpl 的一个实例。

于 2013-07-21T13:53:37.137 回答