@Override和@Transactional注释

时间:2013-07-21 13:02:54

标签: spring spring-mvc jpa

我使用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方法的东西?感谢

1 个答案:

答案 0 :(得分:4)

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

@Autowired
private UserDAO userDAO;

而不是

@Autowired
private UserDAOImpl userDAOImpl;

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