首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@Override和@Transactional注解

@Override和@Transactional注解
EN

Stack Overflow用户
提问于 2013-07-21 21:02:54
回答 1查看 5.1K关注 0票数 1

我使用jpa,eclispelink和Spring3。我有UserDAO接口:

代码语言:javascript
复制
  public interface UserDAO {
    public void saveUser(User user);
  }

和实现类:

代码语言:javascript
复制
@Service
@Transactional
public class UserDAOImpl implements UserDAO{

@PersistenceContext
EntityManager em;

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

当我启动应用程序时,我得到了错误:

代码语言:javascript
复制
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

但是如果我不实现接口:

代码语言:javascript
复制
 @Service
 @Transactional
 public class UserDAOImpl {
 @PersistenceContext
 EntityManager em;
  public void saveUser(User user) {
  em.persist(user);
  }

一切正常。我不明白。也许是因为@Override方法的原因?谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-21 21:53:37

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

代码语言:javascript
复制
@Autowired
private UserDAO userDAO;

而不是

代码语言:javascript
复制
@Autowired
private UserDAOImpl userDAOImpl;

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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17772614

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档