2013-07-21 43 views
1

我使用JPA,eclispelink春季3.我有UserDAO的接口:
@覆盖和@Transactional注解

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方法的东西?由于

+2

我敢肯定,有一些确切的重复的问题http://stackoverflow.com/a/8224772/241986,基本上Spring的默认策略是使用JDK代理如果类实现至少一个接口和CGLIB代理,否则。当使用JDK代理时,您将无法注入该类,只有界面可用。 –

+1

顺便说一句,我认为这个约定是用'@ Repository'注释DAO类而不是'@ Service' – Mina

+0

@BorisTreukhov完全是问题!!我一直在寻找这些奇怪的问题很久 –

回答

4

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

@Autowired 
private UserDAO userDAO; 

,而不是

@Autowired 
private UserDAOImpl userDAOImpl; 

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

+0

我相信第二段代码应该是'私人UserDAOImpl userDAOImpl;'对吗? –

+0

是的。对不起,这个错误。 –